The Command Prompt just hangs after executing my java program - java

It seems like there is no problem with this code (here it is):
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput = new Scanner(System.in);
static int guessedNumber = userInput.nextInt();
public static void main(String[] args) {
start: {
while (guessedNumber != randomNumber) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
delay(1500);
System.out.print("Try to guess it: ");
if (guessedNumber == randomNumber) {
System.out.print("Congradulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
break start;
}
}
}
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
If you couldn't tell already I'm a beginner trying to create a basic number guessing game. So I successfully coded it but now every time I execute it this happens:
It just freezes. Why?

The issue is that you're putting the userInput.nextInt() call in the initializer for a static field; so it gets called (and the program pauses for input) as your class is loading, before it can pribt a prompt requesting the input. So it looks like it froze, but if you enter a number it will then proceed.
You want the nextInt() call to be inside your method after the calls that prompt for input

The error is because your program is waiting for an user input. According to the docs, a Scanning operation may block waiting for input
The solution is implementing a do/while and userInput and guessedNumber initialized when they are required.
NumberGuessingGame:
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput;
static int guessedNumber;
public static void main(String[] args) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
do
{
delay(1500);
System.out.print("Try to guess it: ");
userInput = new Scanner(System.in);
guessedNumber = userInput.nextInt();
if (guessedNumber == randomNumber) {
System.out.print("Congratulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
System.out.println("Error, try again! ");
delay(800);
}
}
while (guessedNumber != randomNumber);
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
Documentation:
do-while statement

its probably waiting for you to enter a number. I conformed its not hanging. its waiting for user input. try entering a number.

Related

how to repeat the loop statement by having a conditional value in java?

What i want to do is, taking input value in variable only0, and the value must be only 0, if the user inputs value 0, then it must show ("we welcome you") line and if not then repeat the same question
System.out.println(" ****Press 0 to start****");
int only0 = sc.nextInt(); //taking input of the user
if (only0 == 0) {
System.out.println(" We Welcome You :-)");
} else {
System.out.println(" YOU ARE REQUESTED TO PRESS ONLY 0 :-)");
}// if end
I like to assume the user is not always going to enter an integer so I load it as a string and then parse to an int to handle off cases.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
int only0 = 0;
try {
only0 = Integer.valueOf(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Only enter an integer! Try again.");
continue;
}
if (only0 == 0) {
System.out.println("We welcome you.");
break;
} else {
System.out.println("You did not enter 0!");
continue;
}
}
scan.close();
}
Unfortunately Java doesn't do that(I suppose you are talking about Goto Statement). However, you can still simulate with recursion without looping statement:
import java.util.Scanner;
public class Test{
Scanner input = new Scanner(System.in);
public static void main(String args[]){
Test run = new Test();
run.ask();
}
private void ask(){
System.out.print("Press 0 to start");
if(input.nextInt()==0){
System.out.println(" We Welcome You :-)");
}
else{
System.out.println(" YOU ARE REQUESTED TO PRESS ONLY 0 :-)");
ask();
}
}
}
In case of invalid input, you need to loop back to prompt the user to enter the value again. One of the best ways to do it is by using a do-while loop as shown below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int only0;
boolean valid;
do {
// Start with assuming that the input will be valid. In case of invalid input,
// assign false to valid which will force the loop to run again
valid = true;
System.out.print("Enter zero: ");
try {
// Use Scanner#nextLine to consume Enter as well
only0 = Integer.parseInt(input.nextLine());
if (only0 == 0) {
System.out.println(" We Welcome You :-)");
} else {
System.out.println(" YOU ARE REQUESTED TO PRESS ONLY 0 :-)");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("This is not a number.");
valid = false;
}
} while (!valid);
}
}
A sample run:
Enter zero: 1
YOU ARE REQUESTED TO PRESS ONLY 0 :-)
Enter zero: a
This is not a number.
Enter zero: 0
We Welcome You :-)

Java, How to break a loop when input is empty? [duplicate]

This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 3 years ago.
The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.
Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....
I'm sure there is a quick and logical solution to this that I'm not thinking of.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
while(scan.hasNextInt()){
int n = scan.nextInt();
if (n > x){
x = n;
}
}
System.out.println("Largets number entered: " + x);
}
}
This should solve your problem:
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
try {
while(!scan.nextLine().isEmpty()){
int num = Integer.parseInt(scan.nextLine());
if(num > x) {
x = num;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Largest number entered: " + x);
scan.close();
}
}
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
String str = scanner.nextLine();
int x = 0;
try {
while(!str.isEmpty()){
int number = Integer.parseInt(str);
if (number > x){
x = number;
}
str = scanner.nextLine();
}
}
catch (NumberFormatException e) {
System.out.println("There was an exception. You entered a data type other than Integer");
}
System.out.println("Largets number entered: " + x);
}
}

Trying to test if an input is odd or even

I'm trying to test if an input is odd or even. The program says that if the input is even keep going, until the input is odd. When it is odd, it stops the program. But the program isn't stopping. Has anyone any idea?
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (isEven()) {
if (isEven()) {
isEven();
} else {
System.out.println(" You added an odd number, done!");
return;
}
}
}
public static boolean isEven(){
int a = scanner.nextInt();
if (a%2 ==0){
System.out.println("You added an even number, go on");
}
return true;
}
}
You'd better simplify all of this, you don't need to call your method multiple times :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (writeAndCheckEven(Integer.parseInt(scanner.nextLine()))) {
System.out.println("You added an even number, go on");
}
System.out.println("You added an odd number, done!");
}
private static boolean writeAndCheckEven(int number) {
return number % 2 == 0;
}
you don't need to use a return if there is no more code after
you can directly use the scanner in the parameter
don't use both while and if it won't do what you want
You should rewrite this code, because code contains incorrect logic.
Correct code for your requirements:
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
int number = scanner.nextInt();
if (isEven(number)) {
System.out.println("You added an even number, go on");
} else {
System.out.println(" You added an odd number, done!");
return;
}
}
}
private static boolean isEven(int number) {
return number % 2 == 0;
}

inputmismatch exception [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
import java.util.*;
public class NGG {
static Scanner numberEntered;
static Scanner userInput = new Scanner(System.in);
static int guessedNumber;
static int randomNumber = (int) (Math.random()* 11);
static Scanner reply;
static String answer;
public static void main(String[] args) {
guessChecker(guessedNumber);
}
public static void guessChecker(int userGuess) {
while (userGuess != randomNumber) {
intro();
userGuess = intChecker();
if (userGuess == randomNumber) {
System.out.println("Congradulations!");
System.exit(0);
} else {
System.out.println("That was Incorrect!");
delay(1000);
retryChecker(reply, answer);
}
}
}
public static int intChecker() {
try {
return userInput.nextInt();
} catch (InputMismatchException e) {
userInput.next();
System.out.println("Your answer was Invalid!");
delay(2000);
retryChecker(reply, answer);
return 0;
}
}
public static void retryChecker(Scanner userReply, String userChoice) {
System.out.println("Would you like to try again?");
userReply = new Scanner(System.in);
userChoice = userReply.nextLine();
if (userChoice.equalsIgnoreCase("yes") || userChoice.equalsIgnoreCase("y")) {
guessChecker(guessedNumber);
} else {
System.exit(0);
}
}
public static void intro() {
System.out.println("I'm thinking of a number in my head...");
delay(1000);
System.out.print("Try to guess it: ");
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {}
}
}
and here's my problem:
I have a number guessing game, every time it says "try to guess it:"
it usually will let you type in a guess, unless your previous guess was a string, letter or number, followed by a space and then another string, letter or number, then instead of letting you write your own guess it will just print out "your answer was Invalid" and move on with the program.
How would I fix this? so that the userInput can also be a string, letter or number, followed by a space and then another string, letter or number and it'll move one with the program normally.
The problem is in the intChecker().
public static int intChecker() {
try {
return userInput.nextInt();
} catch (InputMismatchException e) {
userInput.nextLine(); // -> changed from .next() to nextLine()
System.out.println("Your answer was Invalid!");
delay(2000);
retryChecker(reply, answer);
return 0;
}
}
The reason is when you use next() it returns string when it encounters space or EOF.
So when you give input it's me!, first checks it's and says it's wrong. It asks whether to continue or not next. When you press y to goes to the method and reads the remaining string me!.
Here you have used different scanners userInput and userReply. As the userInput is static, the object doesn't dies and has the remaining string in it which is me! after returning its.
So using nextLine() returns the whole string.
For more info on how they both work, check out my other answer
I hope it helped.

Inputing Integers error throwing

Can someone help me make this code neater. I would rather use parse int than a buffer reader. I want my code to loop until the user inputs a number. I couldn't figure out how to do this without the code printing out the same statement twice.
public void setAge()
{
try {
age = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("What is your age?");
this.setAge();
}
}
Alright, my question is unclear. I am unsure of how to handle the error that a scanner throws when you don't input an integer. How do I handle this? I found "NumberFormatException" in a different post, but I am unsure of what this does. Can anyone help me with this, or is my question still unclear?
Try this:
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
Scanner scanner = null;
int age = -1;
do {
try {
scanner = new Scanner(System.in);
System.out.println("What is your age?");
age = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter a number!");
}
} while (age == -1);
System.out.println("You are " + age + " years old.");
if (scanner != null)
scanner.close();
}
}
I get this output (the first time I enter abc instead of a number to make it retry):
What is your age?
abc
Please enter a number!
What is your age?
35
You are 35 years old.
Have fun!
Use scan.nextInt(); instead of scan.nextLine();
With this, you don't need to parse the line.
EDIT: Oops, i misread your question
Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.
The conversions are done by the functions Integer.parseInt.Consider if you give the value of str is "saurabh", the function call will fail to compile because "saurabh" is not a legal string representation of an int value and NumberFormatException will occurs
You could use a scanner.
You'll need to;
import java.util.*;
static Scanner console = new Scanner(System.in);
You won't need the parse statement at all.
age = console.nextInt();
EDIT: Editing my answer after seeing your edit.
I would put the entire try in a do loop. Using a new boolean variable to control when you come out of it.
boolean excep;
do {
excep = false;
try {
age = console.nextInt();
}
catch (Exception exRef) {
System.out.println("Please input an integer");
console.nextLine();
excep = true;
}
} while (excep);
The console.nextLine() just clears a line so it doesnt re-read the last input. Sometimes it's needed.
Using this i don't receive any error notifications on the running of it.
Try this:
static boolean firstTime = true;
public static void main(String[] args) {
boolean firstTime = true;
setAge();
}
public static void setAge()
{
if(firstTime)
{
System.out.println("What is your age?");
firstTime = false;
}
Scanner scan = new Scanner(System.in);
try{
int age = scan.nextInt();
System.out.println(age);
}
catch(InputMismatchException e)
{
setAge();
}
}
if you want to print different messages you would have to do like:
import java.util.Scanner;
public class Numbers {
public static void main(String args[]) {
Numbers numbers = new Numbers();
numbers.setAge();
}
private boolean alrearyAsked = false;
private int age = 0;
static Scanner scan = new Scanner(System.in);
public void setAge()
{
try {
age = scan.nextInt();
} catch (NumberFormatException e) {
if (alrearyAsked) {
System.out.println("you typed a wrong age, please try again.");
}
else {
System.out.println("What is your age?");
}
this.setAge();
}
}
}

Categories

Resources