I am a beginner and I am confused with using hasNextInt(). If it checks the input, then shouldn't we be using it after asking the user for input? However, in the given code below, it is used with if statement. Please advise.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your number");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
System.out.println("You entered an integer");
} else {
System.out.println("you didn't enter an integer");
}
}
}
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. The scanner does not
advance past any input.
So Scanner would be invoked upon user presses "Enter" and then it would evaluate if the next input provided by user is int or not.
You use it to test the user's input, so you are sure that when you call nextInt you won't have an exception because the input wasn't an int, it's also not moving he cursor forward:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}
Related
I have this code that asks for a name and age in a do-while loop:
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d",
scanner.next(), scanner.nextInt());
} while (scanner.hasNext());
}
}
It outputs:
Enter name & age: test 6
test 6
and then doesn't seem to react to my input, while it should have repeated the question on the third line. What is wrong here?
I think this should stop by the points it gets its input, since when you'll press enter, it would automatically enter the input and your method would end.
I would recommend you to use a while(true) statement if you want to have an infinite input. That issue shouldn't appear if you do it that way.
The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input. Read more
To avoid getting blocked by hasNext() you can simply pass true for loop condition.
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d", scanner.next(), scanner.nextInt());
} while (true);
}
}
I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".
I need this code to produce an error message when the user tries to input a string instead of an int. How would I go about doing that?
import java.util.Scanner;
public class Testing {
public static void main (String [] args){
Scanner s = new Scanner(System.in);
System.out.println("Please enter an int");
input = s.nextInt();
}
}
Check if user provided proper int with hasNextInt() method.
if validation was OK read that value with nextInt().
if value was not int you can use next() to consume it (you don't have to really use that value, but you need to take it out from scanner so you could read other values from user).
Use a loop. Check if there is an int. And if there isn't display a message. Something like,
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Please enter an int");
if (s.hasNextInt()) {
input = s.nextInt();
// ...
break;
}
System.err.printf("%s isn't an int%n", s.next());
}
Ive got a problem.I 'm new to Java,I've started today:D) ..I've programmed before so I know it little bit,but I am new to Java. Here is my code: `
public class Tutorial {
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.nextLine();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
}`
It wants from me 2 numbers,I write them and them it writes "Choose the operation" and its over.No more inputs.Thank you very much :)
Your problem is simple.
Just replace the code with next() instead of nextLine().Effectively, the line your code is returning is receiving is a blank line. Hence when it reaches the conditional statement it has an empty string and terminates.
next()
Finds and returns the next complete token from this scanner.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
Your code should be fixed by a simple change.
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.next();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
Scanner#nextDouble() consumes only the next token as a double from the input. It does not consume the new line you typed using the Enter on the keyboard while entering the two numbers. When the execution reaches operacia=in.nextLine();, this new line is consumed, never allowing the user a chance to type the operating string.
To solve this, you need to read the whole line using Scanner#nextLine() and convert it to a double:
String input = in.nextLine();
num1 = Double.parseDouble(input);
input = in.nextLine();
num2 = Double.parseDouble(input);
I believe the in.nextLine(); operation is reading only to the end of the line where you input 2 numbers. If you want your program to only consider the next line, you have to clear the current one first.
Try this, it should work:
System.out.println("Choose the operation");
in.nextLine(); //clear the current line
operacia=in.nextLine();
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");
}
}