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");
}
Related
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.
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();
}
I want to make my program loop until the user types in x instead of a number. I tried using a while statement but I do not know how to use it with multiple variables. Here is my code
public static void main(String[] args)
{
int denominatorOne = 1, numeratorOne = 1;
System.out.println("Welcome, type an \"x\" at any point to exit the program");
while (numeratorOne !=x)
{
Scanner in = new Scanner(System.in);
//Prompt the user for fraction one
System.out.print("Enter the first numerator (top number): ");
numeratorOne = in.nextInt();
System.out.print("Enter the first denominator (bottom number): ");
denominatorOne = in.nextInt();
}
}
The exact phrasing from my assignment is The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)
First off, 'x' isn't a number and won't be accepted by nextInt or a comparison to 'x', you should trying checking to see if it has next int (in.hasNextInt()) and process depending. Besides the point, you can easily test two variables in a while loop. Assuming you set up the variables right to be chars:
do {
// scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))
what you need to do is have a bool value that holds the loop and when have a if statement check for the keydown event in the loop
bool looping = true
while ( looping == true)
{
if (x button was pressed == true)
{looping = false
}
}
try changing it to
while(!numeratorOne.equals("x")){...}
You can just call the method over again in this case main();.
What I suggest however is to create a new method, in the method just checking the users input returning the input as a string. Then you can check the string in your main method, and if that's not the string you wanted then recall the method. Here's an example, please note I didn't use an IDE for this.
public String getMessage(){
Scanner input = System.in();
return input;
}
public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}
public static void main(String[] args){
checkMessage();
}
Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}
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.