Scanner input = new Scanner (System.in);
System.out.println("Enter -1 to exit the program");
System.out.println("Enter the search key: ");
int searchkey = input.nextInt();
String exit = input.nextLine();
while (!exit.equals("exit"))
{
linear(array, searchkey);
binary(array,searchkey);
System.out.println();
System.out.println("Enter exit to end the program");
System.out.println("Enter the search key: ");
searchkey = input.nextInt();
exit = input.nextLine();
}
I am getting an InputMismatch exception. I know this is because of searchkey. How can I use the string to exit the program?
If "exit" is the first thing you type when you run the program then you will crash. This is because the first read in of the input is input.nextInt(). If you type "exit" and input expects an int, it will throw the InputMismatch exception.
To correct for this, you can use input.next() if you dont know what you are going to get. Then you can do your own parsing on the input.
You are calling nextInt without checking it is an int. You need to check hasNextInt() first because they might have typed "exit" as you instructed.
My guess is you type "exit" immediately after the print statement, so it gets captured by
searchkey= input.nextInt();
If nextInt()gets a non-int passed to it, it will cause an exception.
input.nextInt() expects you to enter an integer (like -1, 0, 1, 2..) If you introduce "exit" then it will throw that exception.
Maybe if you change the position of your prompt and your instructions?
System.out.println("Enter -1 to exit the program");
int searchkey= input.nextInt(); // Only integers are allowed
System.out.println("Enter the search key: ");
String exit = input.nextLine(); //Introduce any string, like exit or apples.
System.out.println will not know what you are going to do, that is something that is meaningful for you, no for the program itself.
This is your current output:
Enter -1 to exit the program
Enter the search key:
<here you should type an integer and enter>
<here you should type a String>
It seems that you don't need the integer at all, but a proper output ought be:
Enter -1 to exit the program
<here you should type an integer and enter>
Enter the search key:
<here you should type a String>
After calling nextInt or nextLine, your console will stop printing until you enter something. If you enter "exit" when nextInt was called you will get that exception, just try to do the math "exit"+5.
Related
I am trying to read only valid integers from the console. I got the example below from another Stackoverflow answer and it should work. If I call the method once it works but on the second call it somehow ignores the sc.hasNextInt() statement and doesn't wait for an input here or thinks there is already an input.
Scanner sc = new Scanner(System.in);
int input;
do {
System.out.println("Please enter a number [0-200]!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next();
}
input = sc.nextInt();
} while (input >= 0 && input <= 200);
sc.close();
return input;
Example of input:
Please enter a number [0-200]!
d
That's not a number!
-1
Please enter a number [0-200]!
That's not a number!
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Aufgabe5.getInput(Aufgabe5.java:44)
at Aufgabe5.main(Aufgabe5.java:112)
nextInt() works in a way that if you input a number and then press Return "The enter key" that key is registered and waiting, when the nextInt() is called again, that registered key will then get consumed by the nextInt() and program will continue without waiting an input, cos it assumed that there was an input. to get around this you can follow the scanner.nextInt() with a scanner.nextLine() to consume that Return key.
other way it can be done by saving a line of code is by replacing scanner.nextInt() with Integer.valueOf(scanner.nextLine()). or better yet, Integer.parseInt(scanner.nextLine())
So apparently removing the sc.close() statement made it work. Idk why though
I have a integer variable but I want it so that
if the user inputs the string 'quit' it will close the program.
public static void input() {
System.out.println("Input: ");
Integer choice = scan.nextInt();
choiceExecute(choice);
if (choice == 'quit') {
goBack();
}
}
Thanks in advance.
Use scan.hasNextInt() to check if the input is a Integer. If so, you can use scan.nextInt(); for getting the integer. If it returns false, you can read the value with scan.nextLine(). If this equals quit, the program should close.
There are a couple things wrong here.
This only searches for Integers:
Integer choice = scan.nextInt();
However, this will return the entire line:
String line = scan.nextLine();
And from this you can do the check to see if it is equal to quit:
if(line.equals("quit"){
// do your processing
goBack();
}else{
Integer num = Integer.parseInt(line);
// do your processing on the number
choiceExecute(num);
}
This is of course making the assumption that you are only storing one item per line and that all other lines that are not equal to "quit" are indeed numbers. Here is how I assume your data looks:
221
357
quit
43
565
quit
One way would be to just read in strings using:
scan.nextLine();
(So you can easily check for "quit").
Then just covert the string to an Integer using:
Integer.parseInt(myString);
I have this programs and a few questions regarding to how .next(), .nextInt(), .hasNext() and .hasNextInt() of Scanner class work. Thank you in advance for any of your help :)
import java.util.Scanner;
public class test {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
int age;
System.out.print("Please enter your age: ");
while (!console.hasNextInt()) {
System.out.print("Please re-enter your age: ");
console.next();
}
age = console.nextInt();
System.out.println("Your age is "+age);
}
}
1/ When !console.hasNextInt() is executed for the first time, why does it ask for an input?
I thought at first the console is empty, so !console.hasNextInt() is True (empty is not an int), then it should go directly from "Please enter your age: " to "Please re-enter your age: " but my thought seems to be wrong.
Here, the user needs to enter something before "Please re-enter your age: " is printed.
2/ The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
3/ For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
The java.util.Scanner.hasNextInt() method returns true if the next
token in this scanner's input can be interpreted as an int value in
the default radix using the nextInt() method.
When you start with a non integer input, hasNextInt() will be false and you will enter while loop. Then it will prompt you to re-enter your age. But if you start with integer, you won't enter the loop. Your age will be printed.
console.next() means it takes next input token and returns String. If you write down your code as:
String s = null;
while (!console.hasNextInt()) {
s = console.next();
System.out.println("You entered an invalid input: " + s);
System.out.print("Please re-enter your age: ");
}
console.next() is being used for handling the non-integer inputs. Now, if you enter a non-integer input twenty, you'll see that console.hasNextInt() will be false and console.next() will read it.
hasNextInt() waits for an input string and then tells you if can be converted to an int. With that in mind, let's go over your questions:
When !console.hasNextInt() is executed for the first time, why does it ask for an input?
Because it blocks until there's some input from the console.
The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
Because hasNextInt() returns true when the input can be converted to an int, for example "21".
For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
Calling next() doesn't wait for a new input, it just swallows the input that was tested by hasNextInt() so the scanner can move on to the next one. It could have been the first statement in the loop, with the same effect.
Im having some trouble with scanning user input in one of my first java programs. When I compile and run this, I am immediately prompted for input (i.e the command line stops and blinks). When I enter anything, the first line is printed, asking me to enter an integer. Then the second line is printed and I'm prompted to enter another value.
The output from this program is the first two values that I input. This is hard to explain, but it basically asks for 3 input values and only uses two.
import java.util.Scanner;
public class objects
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer please...");
int input = sc.nextInt();
System.out.println("Enter your name please...");
String name = sc.nextLine();
System.out.println("The read values: " + input + ", " + name);
sc.close();
}
}
Put a System.out.flush() command after your println statements if you're reading from the console directly afterward
just use this:
Scanner sc = new Scanner(System.in);
System.out.print ("Enter your name please... ");
String name = sc.nextLine();
System.out.print ("Enter an integer please... ");
int input = sc.nextInt();
System.out.println ("The read values: " + input + ", " + name);
i just moved the integer below the name and it sorta fixed it. hahaha
When you introduce a number you press enter key, nextInt() uses the number but the enter (\n) remains buffered. After this if you call again nextInt(), Java tries to convert \n into a number giving you a NumberFormatException, but if you invoke nextLine() they read the enter as empty string
Here you have a better explanation and one solution
Can't use Scanner.nextInt() and Scanner.nextLine() together
It seems this is an error to do with my installation of VirtualBox. No matter what I try, the problem persists. Even if i try to only read ONE integer, it will ask me to input two values.
Thanks for everyone who tried to help, I learned a lot just trying to debug this.
am stuck with this question
6) Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key, 789, the ENTER key. Analyze the following code.
Scanner scanner = new Scanner(System.in);
int value = scanner.nextDouble();
int doubleValue = scanner.nextInt();
String line = scanner.nextLine();
i know the answer, the line will be equal to '\n' when the last statement is executed but why?
can anyone please explain it for me please?
The Scanner reads as many tokens as necessary to get it's next output and then leaves all of the rest of the tokens there to be examined. nextInt() does not need the newline character so it leaves it in the token stream. When you call nextLine() it looks into the token stream, sees the newline character, and returns that.
Let's break this statement by statement.
Scanner scanner = new Scanner(System.in);
int value = scanner.nextDouble();
The system waits for you to type in the value.
34.3↲
The value is read as 34.3 but is truncated to 34 since it is stored as an integer. Now the next statement is executed.
int doubleValue = scanner.nextInt();
The system waits for you again to type in the value.
57.8↲
The value is read as 57 as you are using scanner.nextInt() and hence, the .8 is ignored. There is however a enter remaining in the buffer.
String line = scanner.nextLine();
The system now waits again for the input, and you type in this. The first new line is the remnant from the previous input.
↲
789↲
The scanner first sees the newline character, so it assumes that the line is terminated. So the value is read as \n
Hope this helps.