0

I am trying to create a small program where I can have the program read in a word. If the word has 6 letters, display the word backwards. If not, tell the user how many letters the word has. Do this until the user enters “japan”.

The example output is:

Enter a word > chess

chess has 5 letters

Enter a word > google

Magic six! ELGOOG

Enter a word > japan

Goodbye!

The if statement and the for loop are bypassed for some reason and I'm not sure why. My current code is as such:

import java.util.*; //imports the utilities
public class WordPyramid {
    public static void main(String[] args) {
        String n;
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter a word: "); 

        while ((n = kb.nextLine().toLowerCase()) == "japan" ) {
            int y = n.length();
            {
                if (y == 6) {
                    String reverse = "";

                    for (int i = y - 1; i >= 0; i--) {
                        reverse = reverse + n.charAt(i);
                        System.out.println(reverse);
                    }
                }
                else {
                    System.out.println(n + " has " + y + 1 + " letters ");
                }
            }
        }
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
The Hacker
  • 63
  • 1
  • 1
  • 10

1 Answers1

1

Use: kb.next() instead of kb.nextLine()

Also, to compare to String object you have to use equals() like:
while ((n = kb.nextLine().toLowerCase()).equals("japan")) {

roeygol
  • 4,908
  • 9
  • 51
  • 88
  • 1
    `Scanner#nextLine` is not wrong. It reads the whole line rather than a simple *word* . – Luiggi Mendoza Jan 27 '15 at 21:57
  • @LuiggiMendoza told why – roeygol Jan 27 '15 at 21:58
  • I already say it: it reads the whole line and rather than reading a simple *word* e.g. if your input is *hello world* then `Scanner#nextLine` will return `"hello world"` while `Scanner#next` will return `"hello"` only. Also, `Scanner#next` doesn't consume the character(s) entered by pressing Enter key in the input stream. – Luiggi Mendoza Jan 27 '15 at 22:00
  • Also, the condition in the `while` loop should be with a not equals. – Luiggi Mendoza Jan 27 '15 at 22:05
  • The program still doesnt output the correct output – The Hacker Jan 27 '15 at 22:10
  • This change* doesn't make sense to me, because it won't fix the issues OP has stated and the sentence `"Enter a word: "` doesn't indicate that the user should be able to enter different words, delimited by white space. But keep it if you think it help ... (* the `#nextLine` -> `#next` change) – Tom Jan 27 '15 at 22:12
  • Luiggi and Tom, My code is not doing what is reuqired of it and I'm not sure why, none of the fixes below have worked and thus I need assistance. Please Help – The Hacker Jan 27 '15 at 22:40