Why can I not enter the while loop? (Java) - java

I want to prompt the user to enter their value within the while loop. The error is caused from trying to receive the user's values using input = kbd.nextInt() and then trying to use that object name in the condition within my while loop (caused a deadlock). Therefore, when trying to run it, the console was blank. Thank you for the help!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
Random generator = new Random();
int num = generator.nextInt(100);
int counter = 10;
while (input != num && counter > 0 )
{
System.out.print("Enter your guess at my number ");
input = keyboard.nextInt();
counter--;
}
//close scanner
kbd.close();
}
}

Whenever you use a statement which takes input (in your case - int input = kbd.nextInt();) the Java application stops executing right there and waits for a input from the specified source (System.in here). Try executing the code again and this time input a random number which will be the value of input variable. After that the loop will start.
Also, in this case of the game you should change int input = kbd.nextInt(); to
int input = -1;
That will kill the 1 percent chance of the random number being same as the number entered before the loop (game) starts. Or you could put an if condition checking if input and the random number are equal and if they are take a new random number and check again (in a loop).

With the statement int input = kbd.nextInt(); before the while loop you are already waiting for user input - without prompting the user. I bet you application is waiting for you to enter the first int. Since you are waiting for while loop to start and the application is waiting for you there is a deadlock.
Figure out how to run a debugger to execute your code step by step. It will help a lot.

Related

inputing and validating the tax number in java

I want to take the tax number from a user and check if the number that i am getting is correct but i have a problem .When i run the programm if the user first gives a wrong number(a number with less or more than nine digits) i see the message that i wrote which is correct but when the user gives a correct number after some inputs i see the message again and the loop never stops.If anyone can help me i would appreciate it because i'm stuck :)
enter image description here
enter image description here
The problem occurs when you get the input the 2nd time inside the while loop... Beacuse you aren't actually checking again the TIN number.
I advice you to create a function to check if the TIN is valid and use a while loop to continuously get the input
like so:
public static void main(String[] args) {
System.out.println("Give me your TIN number");
Scanner in = new Scanner(System.in);
long TIN = in.nextLong();
//while the input is not valid ("!" negates the boolean) print invalid input and get the input again
while(!isValidTIN(TIN)){
System.out.println("Wrong number! Try Again");
TIN = in.nextLong();
};
// Countinue with your program
System.out.println("Success");
}
public static boolean isValidTIN(long TIN){
int count = 0;
while(TIN > 0){
TIN /= 10; //You can also use TIN /= 10 instead of TIN = TIN / 10
count++;
}
return count == 9;
}
Also paste the code next time instead of an image

Java Input/output MyProgrammingLab 21212

I am trying to solve a problem in MyProgrammingLab in which I must use a scanner variable named input, and an integer variable named total, to accept all the integer values in input, and put them into total. The program recommends a while loop;however, I have no idea what the condition would be since the scanner is tied to (system.in) instead of a file so it is accepting random user input rather than a predefined string. Can anyone offer advice? Here is the current code I've tried to use:
int number = 0;
while (input.hasNext())
{
number = input.nextInt();
total = number;
}
I am getting a message that literally only reads ("compiler error") while not understand what is going on. I understand that hasnext will not work, but even if I remove it I get the same compile error message; furthermore, I'm not sure what while condition to use without the hasNext method.
I tried changing to input.hasNextLine since two people suggest it may be an EOF reached error, but I'm still getting a compiler error.
/*
I am trying to solve a problem in MyProgrammingLab in which I must use a scanner variable named input,
and an integer variable named total, to accept all the integer values in input, and put them into total.
The program recommends a while loop;
*/
private static Scanner input; //Collect user numbers
private static int total = 0; // to display total at end
private static int number = 0; // Variable to hold user number
private static boolean loopCheck = true; // Condition for running
public static void main(String[] args) {
// Main loop
while(loopCheck) {
input = new Scanner(System.in); // Setting up Scanner variable
// Information for user
System.out.println("Enter 0 to finish and display total");
System.out.println("Enter an Integer now: ");
number = input.nextInt(); // This sets the input as a variable (so you can work with the information)
total += number; // total = (total + number); Continually adds up.
// When user inputs 0, changes boolean to false, stops the loop
if(number == 0) {
loopCheck = false;
}
}
//Displays this when 0 is entered and exits loop
System.out.println("Your total is: " + total); // Displays the total here
System.out.println("Program completed");
}

Is there another way to use hasNextInt() in Java without putting everything in the if-statement?

My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);

Why is output shown only alternately?

public class Two {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
while(obj.nextInt() > 5)
{
System.out.println(obj.nextInt());
}
}
}
If i input the number ( > 5) for first time there is no output on the console but if i input a number on second try there is output on the console.
So I get an output alternatively.
Can anyone explain why is it so?
The java.util.Scanner.nextInt() method Scans the next token of the input as an int and returns it. After the token is read another nextInt()-Call will read (as the name says) the next Integer.
I think you were expecting something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int read;
while((read = scanner.nextInt()) > 5)
{
System.out.println(read);
}
}
Now the read Integer is stored in the variable read and is printed, if it was greater than five.
The reason you're getting output every other input is because you're prompting the Scanner object to gather input twice within your loop system. Every time you call a next... method on your Scanner you are prompting the user.
So in your condition for the while loop you are asking the user to input a value integer value which is then compared against 5. THEN, in your print statement you call the nextInt() method again, which will then prompt the user again for another value integer input.
So given a series of 6 integer inputs for your current loop, 6 2 10 4, you loop will only print 2 and 4.
Instead, you should prompt and store once outside of your loop, then test with the condition and reprompt after the print within the loop like so...
int input = obj.nextInt();
while (input > 5){
System.out.println(input);
input = obj.nextInt();
}

Why isn't the nextInt() method working?

I've typed it exactly as shown in Introduction to Java Programming (Comprehensive, 6e). It's pertaining to reading integer input and comparing user input to the integers stored in a text file named "lottery.txt"
An external link of the image: http://imgur.com/wMK2t
Here's my code:
import java.util.Scanner;
public class LotteryNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Defines and initializes an array with 100 double elements called isCovered.
boolean[] isCovered = new boolean[99];
// Prompts user for input and marks typed numbers as covered.
int number = input.nextInt();
while (number != 0) {
isCovered[number - 1] = true;
number = input.nextInt();
}
// Checks whether all numbers are covered.
boolean allCovered = true;
for (int i = 0; i < 99; i++)
if (!isCovered[i]) {
allCovered = false;
break;
}
// Outputs result.
if(allCovered) {
System.out.println("The tickets cover all numbers."); }
else {
System.out.println("The tickets do not cover all numbers."); }
}
}
I suspect the problem lies within the declaration of the array. Since lottery.txt does not have 100 integers, the elements from index 10 to 99 in the array are left blank. Could this be the problem?
Why does the program terminate without asking for user input?
Possible Solution:
After thinking for a while, I believe I understand the problem. The program terminates because it takes the 0 at the EOF when lottery.txt is feed in. Furthermore, the program displays all numbers not to be covered because the elements from 11 to 100 are blank. Is this right?
The program is written to keep reading numbers until a zero is returned by nextInt(). But there is no zero in the input file, so the loop will just keep going to the end of the file ... and then fail when it tries to read an integer at the EOF position.
The solution is to use Scanner.hasNextInt() to test whether you should end the loop.
And, make sure that you redirect standard input from your input file; e.g.
$ java LotteryNumbers < lottery.txt
... 'cos your program expects the input to appear on the standard input stream.

Categories