Home > Blockchain >  Unable to print or enter a for loop
Unable to print or enter a for loop

Time:09-25

I'm trying to get my code to print the word someone inserts this way. Exemple for hello: h-e-l-l-o

Here is my code:

String word = " ";
String result = " ";
Scanner sc = new Scanner(System.in);

System.out.println("Enter a word:");
word = sc.next();
System.out.println("Your word is "   word);
int wordSize = word.length();
char wordChar = word.charAt(0);

for (int i = wordChar; i <= wordSize; i  ) {
  wordChar = word.charAt(i);
  result = result   wordChar   " - ";
  System.out.println("the result 
    is: "   result);    
  }

CodePudding user response:

You are printing your result in the for loop. Print the result outside of look. Also you need to remove last character from your result as it will be having one extra "-"

String result = "";
for(int i = 0; i < word.length(); i  ) {
   result = result   word.charAt(i)   " - ";
}
result.substring(0, result.length() - 1);
System.out.println(result);

CodePudding user response:

You are doing int i = wordChar into your for loop, what means you are parsing char into int.

The int value is the ASCII one, so your loop will start maybe in a number gretaer than wordSize and the loop is not executed.

To loop over the string you need:

for(int i = 0; i < wordSize; i  ) { }

CodePudding user response:

As others have mentioned, i should be set to 0. Your for loop should iterate for as many characters as you have in word, so you should start at 0 and go as many times as characters you have.

It's important to point out that < in the loop condition should be used instead of <= because we start at 0 and <= will give you one-too-many loops. If this isn't done, you'll hit an error trying to call .charAt(i) on the last iteration of the loop.

Also the print statement needs to be done outside the loop or you will print out more than just "h-e-l-l-o".

Also result should start out as an empty string "" otherwise you'll have a space at the beginning. And " - " shouldn't be added on the last iteration. These can both be solved more easily with a StringJoiner which will allow you to use a hyphen as a delimiter between the characters.

  •  Tags:  
  • java
  • Related