简体   繁体   中英

Why terminal doesn't prompt another input for this JAVA code?

class test {
 public static void main(String args[])
  throws java.io.IOException {

    char ch, answer = 'K';

    System.out.println("I'm thinking of a letter between A and Z.");
    System.out.print("Can you guess it: ");

    ch = (char) System.in.read();

    if(ch == answer) {
     System.out.println(" *** YOU ARE RIGHT *** ");   
       else System.out.println("Please try again: ");
        ch = (char) System.in.read();        
   }
  }

}

I'm using command line to run this java program and I want the user to continuously be able to input something instead of having to run the program manually every time they guess it wrongly. Tried many ways but the second System.in.read() doesn't show a prompt instead the code just ends in terminal having to manually run the program again to play. I'm a beginner so I have trouble understanding.

This will work:

import java.util.Scanner;
class test {
    public static void main(String args[]) throws java.io.IOException {
            char ch, answer = 'K';
            Scanner s = new Scanner(System.in);
            System.out.println("I'm thinking of a letter between A and Z.");
            System.out.print("Can you guess it: ");
            ch = s.next().charAt(0);
            if(ch == answer){
                    System.out.println(" *** YOU ARE RIGHT *** ");
            } else{
                    System.out.println("Please try again: ");
                    ch = s.next().charAt(0);
            }
    }
}

For one, as @GhostCat mentioned, you should put brackets around your if and else cases, otherwise the second read will happen regardless of the if statement

if (ch == answer) {
    // your if code here
else {
    // your else code here
}

Second, if you want it run indefinitely until they give a right answer, you need some kind of loop. In this case, you probably want a while loop. This would replace the if statement

while (ch != answer) {
    // ask for retry
}
// They were right!

The code after the closing bracket will only run once the condition of the while loop is false (in this case, when ch is equal to answer). Meaning, at this point you can handle the correct answer case. Meanwhile, if they input the wrong answer, the program will loop and they will be prompted to try again.

EDIT: As to why the original code wasn't waiting for a second input and just stopping, inputting the first character in the command line actually adds an extra carriage return/new line character to the end of input, so the second read immediately consumes this new line character and proceeds (which in the initial code there's nothing else to do, so it quits).

if(ch == answer) 
     System.out.println(" *** YOU ARE RIGHT *** ");

       else System.out.println("Please try again: ");
        ch = (char) System.in.read();        

is the equivalent of

if(ch == answer) {}
    System.out.println(" *** YOU ARE RIGHT *** ");
} else {
    System.out.println("Please try again: ");
}
ch = (char) System.in.read(); 

Indentation has no effect semantically nor syntactically. It's just a convention but it has no effect on your program (in contrast to python).

You should loop the program:

while(ch != answer) {
    ch = (char) System.in.read();
    ....
}

However, this lacks EOF handling. It's better to use something like this:

while(true) {
   int ch = System.in.read();
   if(ch < 0) {
      System.out.println("Bye!");
   }

   if((char)ch == answer) {
      System.out.println("YOU ARE RIGHT");
      break;
   }

   System.out.println("Please try again: ");
}

Also, bear in mind that read() reads only one byte which depending on how you input the data can be confusing because terminals usually buffer input until you press enter... not all terminals do this but most do it. You might be better of with using System.console which provides a readLine method. However, System.console won't work if no console is attached to stdin (such as when piping input to stdin, but for your case that's not a problem because I don't think your program is intended to be used through pipes). You can use System.console.readLine() and then strip away unwanted characters using the trim method of String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM