Hello, Im trying to write a program for java class and im pretty new to this. here is the code as follows: For some reason im getting this error and Im not sure why. I also need the program to loop so that the user must have the option to press 'Q' or 'q' to quit or any key to continue and my book is not clear at all. Any advice?
Ok, i figured out that the equations after the first if statements needed "{" before and after becuase they were compound but im not sure about the loops yet.
Its the same principle across all languages really. First display the input (before the loop) Then, start a while loop, this should loop whilst your input is NOT equal to q or Q. THen at the end of the while loop, BEFORE it loops, repeat the input request.
I'd put the input request at the top of the loop, so there's no repeated code Code: public static void main(String[] args) { boolean finished = false; String input; Scanner kb = new Scanner(System.in); while(!finished) { System.out.println("Your name?"); input = kb.nextLine(); if(input.equalsIgnoreCase("q")) { finished = true; continue; } System.out.println("Hello " + input); } System.out.println("Quiting"); }
Code: public static void main(String[] args) { String input; Scanner kb = new Scanner(System.in); System.out.println("Your name?"); input = kb.nextLine(); while(input != "q" || input != "Q") { System.out.println("Your name?"); input = kb.nextLine(); System.out.println("Hello " + input); System.out.println("Your name?"); input = kb.nextLine(); } System.out.println("Quiting"); } Using your method, you're adding in extra variables and sub checks, with my method above, there's only one variable. Personally I normally use -1 as a control variable (just because C++ has datatypes) I'm not a Java person, so you may need to fiddle that code to make it work.
I assume you meant to delete the println and nextLine at the top of the while loop? Personally, in a simple program like this, I'd sacrifice a variable and an if condition for the sake of maintainability. Then again, the input request could be performed by a seperate private method which is called before and at the end of the while loop. No duplicated code and it's easier to maintain While we're at, add a static member variable to the class and set it to "q" - get ride of magic numbers/letters.