Use System.in.read() repeatedly - java

New to programming, and I'm trying to create a "Guess the letter" game. The idea is that the first person presses a key, then the second person presses a key to see if she has guessed it right.
Here is my code:
package bookExamples;
public class GuessTheLetterGame {
public static void main(String[] args) throws java.io.IOException{
char answer;
System.out.print("press a key and press ENTER:");
answer= (char) System.in.read();
char guess;
System.out.print("Have a guess and press ENTER: ");
guess = (char) System.in.read();
if (guess == answer)
System.out.println("**Right**");
}
}
It runs okay until the line "Have a guess and press ENTER:", then I tried to press a key again, the code has no reaction.
Thank you in advance :)

By casting a System.in.read() to char you are casting a byte from system to UTF-16. Therefore char c = (char) System.in.read(); will only work for very limited input.
I would recommend using Scanner to read in an entire line.
String answer = "A";
Scanner scanner = new Scanner(System.in);
String guess = "";
while(! answer.equalsIgnoreCase(guess))
{
guess = scanner.nextLine();
}
System.out.println("CONGRATULATIONS YOU WON!");

Here's another one that matches original code intent but provides a Scanner and while loop until there is a match
import java.util.Scanner;
public class GuessTheLetterGame {
public static void main(String[] args) throws java.io.IOException{
Scanner keyboard = new Scanner(System.in);
char answer;
char guess;
boolean right = false;
while(!right){
System.out.print("press a key and press ENTER:");
answer= (char) keyboard.next().charAt(0);
System.out.print("Have a guess and press ENTER: ");
guess= (char) keyboard.next().charAt(0);
if (guess == answer){
System.out.println("**Right**");
right = true;
}
}
}
}

I am also learning Java and wanted a way to make this program work using the commands I know (Scanner is more advanced).
As mentioned by Pshemo and Andreas, the System.in buffer has a 'linefeed' character (ASCII 10) still in it (assuming only a single character for 'answer' was entered).
By 'reading' that character the buffer is emptied and the next time System.in.read() is used it will take an entry as expected. I added 'linFed' to clear it.
package BookExamples;
public class GuessTheLetterGame {
public static void main(String[] args) throws java.io.IOException{
char answer;
System.out.print("press a key and press ENTER:");
answer= (char) System.in.read();
char linFed;
linFed= (char) System.in.read();
char guess;
System.out.print("Have a guess and press ENTER: ");
guess = (char) System.in.read();
if (guess == answer)
System.out.println("**Right**");
}}

In your code there is no loop to keep guessing. It's just a one shot deal. To keep guessing, you need to repeat a part of your code.
package bookExamples;
public class GuessTheLetterGame {
public static void main(String[] args) throws java.io.IOException{
char answer;
answer= 'A';
char guess = '\0';
Scanner scanner = new Scanner(System.in);
while(answer != guess) {
System.out.print("Have a guess and press ENTER: ");
guess = scanner.next().charAt(0);
System.out.println(guess);
}
System.out.println("**Right**");
}
If you keep guessing until the answer is right, you no longer need the if statement. The only thing left to keep the formatting correct, is to show the user their guess and start a new line.
NOTE: changed the code to use a scanner, and scanner.next() to get one character at a time.

Related

Java:If user type 'y'||'Y' quiz begins,'n'||'N' quiz end.For rest,it shows invalid. I want to show invalid when user type word starting with y or n

I want the program to run only if it recieves 'y','Y','N' or 'n'. It doesn't work for other characters . However when user writes a more than 1 letter word with y or n (for e.g yddh,ndhdh, etc), the program still runs. please suggest what I can do. I tried taking 'a' as String but in if-else statement it showed error because string cannot be compared to char with == operator.
import java.util.Scanner;
class Main {
static char a;
public static void main(String[] args) {
System.out.println("Do you want to play this quiz?");
System.out.println("Type 'Y'for Yes or 'N' for no. It's case Insensitive.");
Scanner sc=new Scanner(System.in);
a=sc.next().trim().charAt(0);
if (a=='n'||a=='N')
{System.out.println("Thanks for downloading!");
System.exit(0);}
else if ((a !='n'&&a !='N') && (a !='y'&& a !='Y'))
{System.out.println("Invalid Syntax");
System.exit(0);}
else if(a=='y'||a=='Y')
{System.out.println("Welcome to the quiz");}
}
}
Further to Subramanian Mariappan's and Yasham's answer, you can shorten the code by using equalsIgnoreCase() method as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Do you want to play this quiz?");
System.out.println("Type 'Y'for Yes or 'N' for no. It's case Insensitive.");
Scanner sc = new Scanner(System.in);
String userInput = sc.next();
if (userInput.equalsIgnoreCase("N")) {
System.out.println("Thanks for downloading!");
System.exit(0);
} else if (userInput.equalsIgnoreCase("Y")) {
System.out.println("Welcome to the quiz");
} else {
System.out.println("Invalid Syntax");
System.exit(0);
}
}
}

Java while loop is doing three iterations by default

I am beginning to learn Java and trying the while loop, I have written a simple program as a simple guessing game where the user tries to guess a letter between A and Z and the computer will print "correct" and repeats if the guessed letter is wrong, however, every time I try to run it the output is three iterations by default, I have tried to change the while loop to do-while and got the same output, I even added the int variable i as a counter to see if its really doing 3 iterations and the value of i always comes as 4 (3 wrong iterations when really it should be 1 plus one when I enter the correct answer).
Can you tell me what is the mistake I am doing?
class Guess {
public static void main (String[] args) throws java.io.IOException {
char answer = 'K', ignore, ch = 'a';
int i=0;
while (ch != 'K') {
System.out.println("I am Thinking of a letter between A and Z, can you guess it?");
ch = (char) System.in.read();
if (ch !='K')
System.out.println("Wrong ! please try again");
i++;
}
System.out.println("Correct!, you guessed after "+i+" attempts");
}
}
The issue is, when you press Enter after typing the character in the console, the loop is executing once for the entered character and again once for the newline which is 10.
So I just edited your code to skip the new line and wait for the next character to be entered, Also I moved the initial prompt outside of the loop. I hope this code would fix your issue:
public static void main(String[] args) throws IOException {
char answer = 'K', ignore, ch = 'a';
int i = 0;
System.out.println("I am Thinking of a letter between A and Z, can you guess it?");
while (ch != 'K') {
ch = (char) System.in.read();
if(!Character.isLetter(ch)){
continue;
}
System.out.println("Wrong ! please try again");
i++;
}
System.out.println("Correct!, you guessed after " + i + " attempts");
}
This is how it should look like.
Your code just missed the else block which is very necessary to break out of the loop,when the user guess the right character.I have added one.
class guess {
public static void main (String[] args) throws java.io.IOException {
char answer = 'K', ignore,ch='a';
int i=0;
while (ch != answer) {
System.out.println("I am Thinking of a letter between A and Z, can you guess it?");
ch = (char) System.in.read();
i++;
if (ch !=answer) {
System.out.println("Wrong ! please try again");
}
else{
System.out.println("Correct!, you guessed after "+i+" attempts");
break;
}
}
}
}
Hi there I got a tip for you.
I personally would use a Scanner instead of System.in.read. A Scanner is an object that reads an input.
To create one, simply tipe this:
Scanner sc = new Scanner(System.in); //System.in referes to a console input
To know what the user typed use sc.nextLine();, which returns, as I said, the input. However it returns a String, not a char. So, in this case, you also needed to change the type of 'ch'.
To compare the answers with the input you will need to used the method equals(). Basically, if two things are the same, it returns true.
That said, your code should look like this:
Scanner sc = new Scanner(System.in);
String answer = "K",ch;
int i=0;
boolean correct = false;
while (!correct) {
System.out.println("I am Thinking of a letter between A and Z, can you guess it?");
ch = sc.nextLine();
i++;
if (!ch.toUpperCase().equals(answer)) { // or ch.equals(answer) == false
System.out.println("Wrong ! please try again");
}else{ //if they are the same
correct = true; //the answer is correct so you can leave the while loop
System.out.println("Correct!, you guessed after "+i+" attempts");
}
}
sc.close(); //you should always close a scanner after you use it, but you can ignore this step for now
Note that I also used a method called toUpperCase(). That method transform all the characters of the string to upper case, so, even if you type "k" instead of "K" you would also quit the loop.

How to stop storing integers and special characters in String in Java?

I wrote a program to read username from keyboard. When I enter any integer or special characters, it is taking that values and displaying on console. But I want that it should not take any integers and special characters. It should take only letters and if any integer or special character is there, then it should give the error message and should not store that value. Can anybody help me with this problem?
The program program which I wrote is
import java.util.Scanner;
public class CheckIsEmpty {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter User Name:: ");
System.out.println();
String usn = sc.nextLine();
if (usn.trim().isEmpty()) {
System.out.println("Don't Give Space");
System.out.println();
}//if
else if (usn.isEmpty()) {
System.out.println("User Name Is Mandatory");
System.out.println();
} // if
else {
System.out.println("Hi " + usn);
System.out.println("Welcome To Java");
break;
}// else
}//while
}//main
}// class
You can use regex here. If all characters are letters then following code will return true.
usn.matches("[a-zA-Z]+")
If an input string is having any other char it will return false.
Hope it helps.
You can use pattern matching..
boolean b = Pattern.compile("[a-zA-Z]+").matcher(username).matches();

Why does this do-while loop not produce the right output?

public static void main(String[] args) throws IOException {
System.out.println("Hello, come and play a game with me!");
int x = 5;
int guess;
do {
System.out.println("Please input a number...");
guess = System.in.read();
guess = System.in.read();
if (guess < 5) {
System.out.println("You guessed the number!");
break;
}
} while (guess > 5);
}
So here I wrote some code. It's supposed to be a guessing game, but no matter what I input, it always gives me in the output "Please input a number..." NO MATTER WHAT I PUT. Basically, if the "guess" is more than 5, then they guessed the number. If it's not, then they haven't guessed the number. That's the premise of the game. Can someone help me fix my code, so it doesn't just output the same thing regardless?
System.in.read(); gives you char. so when you enter "1", it gives you its char value, 49. so you can not enter integer 5 with typing numbers. so change your reading method. you can use Scanner
You are doing the opposite - an answer less than 5 is accepted as correct.
Here is a working version of your code.
As mentioned in previous answers, the System.in reads in characters so you cannot read in numbers directly. Below The code is leveraging the BufferedReader API whitch works on an InputStream.
public class App {
public static void main(String[] args) throws IOException {
System.out.println("Hello, come and play a game with me!");
int x = 5;
int guess;
do
{
System.out.println("Please input a number...");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
guess = Integer.parseInt(br.readLine());
if(guess < 5){
System.out.println("You guessed the number!");
break;
}
} while(guess>5);
}
}
it looks like you did not use the variable x, try using the Scanner class to get input from the user
public static void main(String[] args) throws IOException {
System.out.println("Hello, come and play a game with me!");
int guess;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input a number...");
guess = input.nextInt();
if (guess < 5) {
System.out.println("You guessed the number!");
break;
}
} while (guess > 5);
}

Using chars, created by a scanner

I'm trying to make a basic text game in Java. I decided just to make a game off of the console because that's the only way I know how. I'm trying to use chars to see if what the user typed contains the letter h at position 0, it worked fine when I tried it in the main method, but it's not working when I call it as a separate method.
import java.util.Scanner;
public class testing
{
static Scanner kb = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Wanna start the game?");
System.out.println("1. Start");
System.out.println("2. Quit");
int ans = kb.nextInt();
if(ans == 1)
{
levelOne();
}
else
System.out.println("Quitting");
}
public static void levelOne()
{
System.out.println("Type something");
char letter = kb.nextLine().charAt(0);
if(letter == 'h')
{
System.out.println("contains h");
}
else
System.out.println("does not contain h");
}
}
Because nextInt doesnt consume any non-numeric input you need to consume the newline characters passed by the method before nextLine is invoked
kb.nextLine(); // added
char letter = kb.nextLine().charAt(0);
remove spaces first then get the character
char letter = kb.nextLine().trim().charAt(0);
input 1 hello
notice space before hello
Output:
Wanna start the game?
1. Start
2. Quit
1 hello
Type something
hello
does not contain h

Categories