Search code examples
javaspell-checkingspelling

Using Scanner object for spell checking as a newbie


Scanner kb = new Scanner(System.in);
String plt;
String msr;
double wgh;

 System.out.println("'Welcome to interplanetary weight calculator.");

 Thread.sleep(2500);


 System.out.println("");
 System.out.println("Please choose one planet for calculation:");
 System.out.println("1.Venus   2.Mars    3.Jupiter");
 System.out.println("4.Saturn  5.Uranus  6.Neptune");
 System.out.print(">");

do { 
 while (!kb.hasNextLine()) {
        System.out.println("That's not a planet!");
        kb.nextLine(); // this is important!
    }
    plt = kb.nextLine();
} while (plt.equalsIgnoreCase("Venus"));
System.out.println("Thank you!Now will do calculation on " + plt); }}

I want to make a weight calculator between planets and I also want a spell checker too but when I write something, it just prints out "Thank you! Now, will do the calculation on ....".

It prints out integers too. I can't find where did I do wrong.


Solution

  • Essentially, what happens is that your loop will run once, you can enter something and it will then exit the loop because anything except "venus" (in any combination of upper and lower case) will exit the loop. This is why it will also print numbers, etc.

    The solution to this might be to add an ! to the beginning of the condition. This will invert the condition, meaning now only entering "venus" will cause the loop to exit which will result in the program continuing to run everything below the loop. However, there's still not going to be any kind of error message. Spell-checking and error handling would be achieved differently.