-2

I just want continue a program when a user presses the y key with a do while loop in this code e.g. while('o'!=='y'). I have also tried this:

public class clac {
     do {     
         System.out.println("\nwant to try again\n press y/n");
         String o;
         o=sc.next();
     } while(!o.contentEquals("y"));
}
Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
  • 1
    Possible duplicate of [How to read a single char from the console in Java (as the user types it)?](https://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) – Hovercraft Full Of Eels Jul 23 '18 at 11:55
  • The duplicate by @HovercraftFullOfEels is exactly right. The problem here is simply that nothing is forwarded to `System.in` if the user does not enter a new line. Raw mode fixes that problem. – Ben Jul 23 '18 at 11:57
  • @Ben Depends on what OP want. – user202729 Jul 23 '18 at 11:58
  • 1
    I would just vote to close as "unclear what you're asking", as OP didn't specify what's wrong with the code (compile error? Not react to a key pressed? etc.) – user202729 Jul 23 '18 at 11:59

1 Answers1

0

use below code if you want to ask question on "y" input :

   public static void main(String r[]) throws IOException {
        Scanner sc = new Scanner(System.in);
        String o;
        do {     
             System.out.println("\nwant to try again\n press y/n");
             o=sc.next();
         } while(!o.contentEquals("y"));
    }

Hope that it is what you are looking for.

dangi13
  • 1,275
  • 1
  • 8
  • 11
  • 1
    Small note: It should be `!o.equals("y")` The loop should end when y is pressed, not continued. –  Jul 23 '18 at 12:01
  • Answers can be more useful if you explain what have you changed from OP's code and why. – user202729 Jul 23 '18 at 12:04
  • I have just declared String o; above the do {} statement and that's it only. no more change. @Vipul have declared it as a local variable inside do statement and it is not getting recognized in while statement. So I have declared it above do statement so that it can be recognized by while statement also. – dangi13 Jul 23 '18 at 12:11
  • updated answer for that change. You can see that no change is made other then placing String o; over do statement. – dangi13 Jul 23 '18 at 12:14
  • @Vipul please do let me know if it solved your problem. – dangi13 Jul 23 '18 at 12:15