Conditionals and Loops reverseword what am I missing? - java

I want to get the desired outputs like here Tests 1-4 and still prompt the user to input the tests using the Scanner scan = new Scanner(System.in). My program says out of range. How should I fix this?
public static void main(String[] args){
String word="";
System.out.println("Enter a Word:");
Scanner scan = new Scanner(System.in);
word= scan.next();
for (int j=word.length(); j>=0; j--) {
System.out.println(word.substring(j-1, j));
}
}

new StringBuilder(scan.next()).reverse().toString();

Try this:
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
Explanation: In your for loop j should only decrement till j>=1. When
j = 1 Because you do substring(j-1, j) = substring(0, 1)
In your case, when j becomes 0, substring(j-1, j) = substring(-1, 0)
Hence the exception, as string does not have -1 as an index.

The error is due to last iteration of loop when j=0 in this case you are doing word.substring(j-1, j) ie word.substring(-1, 0) Giving you that error.
Instead change the loop to j>=1
String word = "";
System.out.println("Enter a Word:");
Scanner scan = new Scanner(System.in);
word = scan.next();
System.out.println();
for (int j = word.length(); j >= 1; j--) {
System.out.print(word.substring(j - 1, j));
}
DEMO

I don't see the point of making a substring each time. Simple charAt(index) would do.
Scanner scanner = new Scanner(System.in);
String word = scanner.next();
for (int i = word.length() - 1; i >= 0; i--) {
System.out.print(word.charAt(i));
}

Related

Print a rhombus pattern from user input

I have a task to ask user for input (user's name) and then to print a rhombus pattern out of it.
For example:
If user's name is Thomas, then the output should be like this:
T
Th
Tho
Thom
Thoma
Thomas
homas
omas
mas
as
s
This is my code so far. I am having trouble with second for loop. I can easily print out lines until "Thomas", but I don't know, how to print whitespace infront so that the end of the word will be on the same place.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
for (int j = 1, k = 1; j <= enteredNamesLength; i++, k++) {
System.out.println(k * " " + name.substring(j, enteredNamesLength));
}
}
}
}
I think there must be one for loop to print the name like what you did, then another for space and inside the same print the substring.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
}
for(int i = 1;i <= enteredNamesLength; i++ ) {
for(int j = 0;j < i; j++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
}
It would be easier to do it in 2 times : substring from start to an index, and then print the spaces followed by the end of the world, ans some changes to do :
no need to cast i as int, it's already an int
first loop : start index i at 1 and not 0, no avoid empty line
second loop : end index for i at enteredNamesLength-1 and not enteredNamesLength to avoid also an empty line
for (int i = 1; i <= enteredNamesLength; i++) { // start at 1
System.out.println(name.substring(0, i)); // don't cast
}
for (int i = 1; i < enteredNamesLength; i++) { // stop at enteredNamesLength-1
for (int space = 0; space <= i; space++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
Here is another solution, you can extract a print method which accepts a start and stop. If the index between them, then print character at index, otherwise print whitespace.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int start = 0, stop = 0; start < enteredNamesLength && stop < enteredNamesLength; ) {
print(start, stop, name);
if (stop < enteredNamesLength - 1) {
stop++;
} else {
start++;
}
}
}
private static void print(int start, int stop, String name) {
for (int index = 0; index < name.length(); index++) {
if (index >= start && index <= stop) {
System.out.print(name.charAt(index));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
You can combine the upper increasing part and the lower decreasing part in one loop.
Try it online!
public static void main(String[] args) {
String str = "RHOMBUS";
int n = str.length();
// two parts: negative and positive
for (int i = 1 - n; i < n; i++) {
// leading whitespaces for the positive part
for (int j = 0; j < i; j++) System.out.print(" ");
// negative part: str.substring(0, n + i);
// positive part: str.substring(i, n);
String sub = str.substring(Math.max(0, i), Math.min(n + i, n));
// output the line
System.out.println(sub);
}
}
Output:
R
RH
RHO
RHOM
RHOMB
RHOMBU
RHOMBUS
HOMBUS
OMBUS
MBUS
BUS
US
S
See also: Writing a word in a rhombus / diamond shape
This code works with both regular UTF8 characters and surrogate pairs.
Try it online!
public static void main(String[] args) {
String str = "π—₯π™·π™Ύπ™Όπ™±πš„π—¦";//"RHOMBUS";
int n = (int) str.codePoints().count();
// two parts: negative and positive, i.e.
// upper increasing and lower decreasing
IntStream.range(1 - n, n)
// leading whitespaces for the positive part
.peek(i -> IntStream.range(0, i)
.forEach(j -> System.out.print(" ")))
// negative part: range(0, n + i);
// positive part: range(i, n);
.mapToObj(i -> str.codePoints()
.skip(Math.max(0, i))
.limit(Math.min(n + i, n))
.mapToObj(Character::toString)
.collect(Collectors.joining()))
// output the line
.forEach(System.out::println);
}
Output:
π—₯
π—₯𝙷
π—₯𝙷𝙾
π—₯𝙷𝙾𝙼
π—₯𝙷𝙾𝙼𝙱
π—₯π™·π™Ύπ™Όπ™±πš„
π—₯π™·π™Ύπ™Όπ™±πš„π—¦
π™·π™Ύπ™Όπ™±πš„π—¦
π™Ύπ™Όπ™±πš„π—¦
π™Όπ™±πš„π—¦
π™±πš„π—¦
πš„π—¦
𝗦

Array is printing each letter of a word on separate line, how to fix?

I'm currently working on an assignment for school and the objective is to have the user input n amount of lines and then print them in reverse.
For example:
"Please enter number of lines: "
3
"Please enter the lines: "
Hi
Hey
Howdy
Desired Output:
Howdy
Hey
Hi
My output:
H
o
w
d
y
H
e
y
H
i
I'm not sure what's wrong and I'd really like some help, here is my code:
import java.util.Scanner;
public class ReverseOrder {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the number of lines: ");
int numberOfLines = kb.nextInt() + 1;
String inputLines[] = new String[numberOfLines];
System.out.println("Please enter the lines: ");
for (int i = 0; i < numberOfLines; i++) {
inputLines[i] = kb.nextLine();
}
System.out.println("Lines in reverse: ");
for (int i = numberOfLines - 1; i >= 0; i--) {
for (int j = 0; j <= inputLines[i].length() - 1; j++) {
System.out.println(inputLines[i].charAt(j));
}
}
kb.close();
}
You are printing each character with an end of line character by calling println() with your current two for loops. This is one step too many.
Since you already have the entire string, you can simply print the strings in reverse order like so using the println() function
for(int i = numberOfLines - 1 ; i>=0; i--){
System.out.println(inputLines[i]);
}
#Kody
I'm not sure what you have to do in your code but:
If you need just print each line in a reverse order, you can do this:
System.out.println("Lines in reverse: ");
for (int i = numberOfLines - 1; i >= 0; i--) {
System.out.println(inputLines[i]);
}
The method println will create a new line for you.

Output displayed automatically without doing anything

So , I am trying to create a program which calculates the score of an exam . What we have to do is give a pattern as a string consisting X's and 0's i.e 000XXX000XXX, where the value of 'X' is 0 and the value of each zero is 1 and for every consecutive '0' the value increases by 1 . If suppose there are 2 or more consecutive 0's and then an 'X' the value of '0' is reset to 1.if the program seems common to you , then , yes this is a problem from an OJ and it was given to me by a senior from my university to solve.Now the thing is I have figured out how the code works and solved the problem.But there seems to be an issue in the code.
package javaapplication4;
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T, score = 0, f = 0, g = 0;
String str;
int len;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
str = sc.nextLine();
len = str.length();
for (int j = 0; j < len; j++) {
if (str.charAt(j) == '0') {
f++;
score = score + f;
}
else if(str.charAt(j) == 'X')
{
f = 0;
score = score + g;
}
}
System.out.println(score);
}
}
}
As you can see from the code , I first give an Input for the number of test cases and as soon as I press enter , the code displays the value of score (which is 0) automatically without doing any think inside the for loop.
I have rechecked all the curly braces, but I cannot find the bug in the code. I would be happy if I could get some help.
Output:
4
0
The sc.nextInt() causes the sc.nextLine() to be triggered so you get the output of a empty string that's why it's zero, by using sc.nextLine() for input of your test case number you can prevent this:
int score = 0;
System.out.println("Enter test case:");
int testCase= Integer.parseInt(sc.nextLine());
for (int i = 1; i <= testCase; ++i)
{
System.out.println("Enter pattern:");
String str = sc.nextLine();
for (int j = 0; j < str.length(); j++)
{
if (str.charAt(j) == '0')
{
score += 1;
}
else if (str.charAt(j) == 'X')
{
score += 0;
}
}
System.out.println(score);
score = 0; // reset score to zero for the next test case
}
See this link regarding the sc.nextInt() issue : Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Showing Exception error for the given code snippet

I'm working on a code in which an input String is taken and an input character is taken. the code will calculate the percentage occurrence of that character in that String. the code is given below:
import java.util.Scanner;
class apple{
public static void main(String args[]){
int i,j,l=0;
float m;
char k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String");
String str = in.nextLine();
j=str.length();
System.out.println("Enter the character to be found");
char s = in.next(".").charAt(0);
for(i=0;i<=j;i++){
k = str.charAt(i);
if(k == s){
l++;
}
}
m= l/j;
m=m*100;
System.out.println("percent character in String is "+m);
}
}
Change your loop to
for(i = 0 ;i < j ; i++)
Otherwise, if your String has a length of 4 (so the last index is 3), it will try to reach index 4 and throw an Exception.
You are doing this:
for (i = 0; i <= j; i++) {
and this is throwing an java.lang.StringIndexOutOfBoundsException:
because you are not considering that the element goes from 0 to lengt-1
instead you should do:
for (i = 0; i < j; i++) {
Edit your for-loop to for (i=0;i<j;i++). We can not access the element at array size position because Java array uses 0-based index
The first character of a String is '0', the last is yourString.length()-1, so change your loop to
for( i = 0 ; i < j ; i++ ){
k = str.charAt(i);
if(k == s){
l++;
}
}
It'll work ;)

how to repeat a process in a specific order?

I want to make the program print for any integer that I input an asterisk in such way that every new line there is an increasing number of two more asterisks, always starting from one asterisk.
This code will print for any integer the same number of lines that I entered, with one asterisk in it, but how do I increase the number of the asterisks in each line?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a number:");
int num = sc.nextInt();
int j=0;
int star=1;
int space= num;
System.out.println ("* ");
if (num>0) {
for (j=1; j<num; j=j+1) {
System.out.println ("* " );
}
for( j=0; j<star; j++) {
}
}
}
public static void main(String[] args) {
String line = "* "; // let's use a variable for the next line we want to print
Scanner sc = new Scanner(System.in);
System.out.println("enter a number:");
int num = sc.nextInt();
if (num > 0) {
System.out.println(line);
for (int j = 1; j < num; j++) { // j++ does the same as j = j + 1
line = "*" + line; // add a * at the start of the line
System.out.println(line);
}
}
}
System.out is a PrintStream. PrintStream has a second method, print that prints out what you put but without printing out the end of line character after it.
So, you probably want to use that instead.
Now, having said that, you'll still need to print out the end of line character when you've finished with the other characters. You can do that by calling the no argument version of println (which looks like System.out.println();)
Assuming you're looking for something like this:
INPUT: 4
*
**
***
****
Then you can do something like this:
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
for (int i = 0; i < num; i++) {
for (int j = 0; j < i; j++) {
System.out.Print("*");
}
System.out.Println();
}
Note that this prints out only one star at a time, and will be fairly slow. Fun to watch though, if toss a sleep statement in there.
You should use two for loops for that, one for lines and another for stars.
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i; j++) {
System.out.Print("*");
}
System.out.Println();
}
Output:
=======
*
**
***
****
*****

Categories

Resources