Reputation: 69
So in this do while code the boolean is an input of the user, but it's only needed one input. If the user press [c] the do while continues but if press any other key stops. I have already the code to do with a String c = "";
but I want to be done with a char
.
Also the other problem happens when I use char c [];
it's not possible to use the c = kb.next().toUpperCase();
Here is the exemple code I did.
Scanner kb = new Scanner(System.in);
String c = "";
do {
//some code.
//here asks to the user to continue or not.
System.out.println("Press [c] to continue, any key to exit.");
c = kb.next().toUpperCase();
} while ( c.equals == ("C") );
Maybe it's already aswered I tried to find an answer... Maybe I'm to Junior. But I wan't to know how I can do it. (please if it's already duplicate tell me don't unvote)
Upvotes: 1
Views: 1213
Reputation: 726939
If you would like to use char c
instead of String c
, this code:
char c;
do {
System.out.println("Press [c] to continue, any key to exit.");
c = kb.next(".").toUpperCase().charAt(0);
} while (c == 'C');
The idea is to pass "."
to next(...)
method to consume exactly one character.
Upvotes: 1
Reputation: 1006
Yes this is possible, very close. You need to compare strings using the String.equals, or String.equalsIgnoreCase rather than what you attempted. Refer to How do I compare strings in Java?
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String c = "";
do {
//some code.
//here asks to the user to continue or not.
System.out.println("Press [c] to continue, any key to exit.");
c = kb.next().toUpperCase();
} while (!c.equalsIgnoreCase("C"));
}
With chars
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
char chr;
do {
//some code.
//here asks to the user to continue or not.
System.out.println("Press [c] to continue, any key to exit.");
chr = kb.next().toCharArray()[0];
} while (chr != 'c');
}
Upvotes: 1