I am new to java programming, and i am trying to learn about different methods available in Scanner class, i came to hasNextInt(); method,does this method has any default values,either true or false,since in the code, first compiler prints "Enter your year of birth:",then compiler moves to next Line that is , boolean hasNextInt = scanner.hasNextInt();,at this point what compiler will do since it has no input?.
This code is working fine,for example if i give invalid input to yearOfBirth ,like "abc" it prints "Unable to parse year of birth.",and when i give valid integer input it works fine too.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your year of birth:");
boolean hasNextInt = scanner.hasNextInt();
if(hasNextInt) {
int yearOfBirth = scanner.nextInt();
scanner.nextLine(); // handle next line character (enter key)
System.out.println("Enter your name: ");
String name = scanner.nextLine();
int age = 2018 - yearOfBirth;
if(age >= 0 && age <= 100) {
System.out.println("Your name is " + name + ", and you are " + age + " years old.");
} else {
System.out.println("Invalid year of birth");
}
} else {
System.out.println("Unable to parse year of birth.");
}
scanner.close();
}
To quote the Javadoc:
Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
In other words, the hasNextInt method will block (wait) if necessary until input is received.
Related
This question already has answers here:
Scanner close after use
(2 answers)
Closed 3 years ago.
When I run my code, it will run fine up to the line "scanner.close()".
After than, when I run the "SumTenNumbers()" method... it will run the first line of the while loop once and crash with the "NoSuchElementException"...
When I remove the code above the line calling the method, it runs fine...
Why does this occur, and how can I solve it?
This is the code:
public class Main
{
public static void main(String[] args)
{
// we use the class "scanner" for input data
Scanner scanner = new Scanner(System.in); //System.in allows you to type input data into the console which can be returned into the console
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Your name is " + name);
System.out.println("Enter your year of birth: ");
boolean isInt = scanner.hasNextInt();
if (isInt)
{
int yearOfBirth = scanner.nextInt();
int age = 2019 - yearOfBirth;
if (age >= 0 && age <= 120)
{
System.out.println("You are " + age + " years old");
}
else
{
System.out.println("Invalid year of birth");
}
}
else
{
System.out.println("Unable to parse year of birth");
}
scanner.close(); // we must close scanner
SumTenNumbers();
}
public static void SumTenNumbers()
{
var reader = new Scanner(System.in);
int sum = 0;
int count = 1;
while (count < 11)
{
System.out.println("Enter number " + count + ": ");
boolean valid = reader.hasNextInt();
if (valid)
{
int userNum = reader.nextInt();
sum += userNum;
count++;
}
else
{
reader.next();
System.out.println("INVALID");
}
}
System.out.println(sum);
reader.close();
}
}
This is how it looks when I run the code...
Enter your name:
Siddharth
Your name is Siddharth
Enter your year of birth:
2001
You are 18 years old
Enter number 1:
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 com.company.Main.SumTenNumbers(Main.java:64)
at com.company.Main.main(Main.java:39)
Process finished with exit code 1
the line reader.close() closes the Scanner and, with it, System.in.
After that, you cannot read from stdin (System.in) anymore.
In order to prevent this you can:
use only one Scanner object and close it after using it the last time
close System.in after using it the last time (using a Scanner or System.in.close())
close System.in at the end of your Program
never close System.in (Problem: other Processes cannot use the resource, stdin can also be a File, a Network Connection or something else)
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
First of all, apologies for the title gore.
The specific thing I am trying to understand here in the following piece of code is why the getNumber function, when called the second time, continues to return the same initial user input and doesn't ask for a new user input.
/*Write an application that inputs one number consisting
of five digits from the user, separates the number into its individual digits and prints the digits
separated from one another by three spaces each.
*/
public class SeparatingDigitsOfInt {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
boolean check =false;
String s=null;
while (check==false)
{
s= Integer.toString(getNumber()); //since user input was a string, getNumber returns 0 and we enter the while loop below
while (s.equals("0"))// here i am trying to get another input from user because first input was invalid
{
System.out.println("Try that again!");
s= Integer.toString(getNumber()); // why getNumber continues to return xyz here and doesn't ask for new user input
check =false;
}
check =true;
}
System.out.println(s);
while(s.length()!= 5){
System.out.println("Input number is not of 5 digits!");
System.out.println("Please enter a 5 digit number");
s = input.next();
}
String result = "";
for (int i = 0; i < s.length(); i++) {
result= result + s.charAt(i) + " ";
}
System.out.println("Result is :" + result);
}
public static int getNumber(){
try {
System.out.println("Enter a 5 digit number");
return input.nextInt(); // user inputs string xyz
}
catch (InputMismatchException e) {
System.out.println("Please enter only numbers");
return 0;// since user inputs xyz, so 0 is returned by getNumber
}
}
}
In documentation stated :
If the translation is successful, the scanner advances past the input
that matched
So that means if it translation was not successful, it won't advance
I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = checkInput(in, "Enter an integer and a base: ");
int inputBase = checkInput(in, "");
}
public static int checkInput(Scanner in, String prompt) {
System.out.print(prompt);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, that is an invalid input.");
System.out.print(prompt);
}
return in.nextInt();
}
This method works and doesn't return any bad input i.e., ; p "hello".
My question is how can I limit the number of inputs the scanner will read. Say I input 5 five % ; but I only want 5 and five to be passed in to my method and the rest dropped.
I looked through the Java API but couldn't find a method that would limit the amount of user input accepted. Am I just missing it or is there another way to do this?
Edit: I have tried using the .length() method to limit the input but then that doesn't allow integers greater than the .length() parameter.
Here is a working sample of how you could accomplish what you need. I broke it up so that the user is prompted once for each input which makes it easier to validate. I changed your checkInput method to getInput which only returns valid user input as a String where it is then converted into an int.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = Integer.parseInt(getInput(in, "Enter an integer: "));
int inputBase = Integer.parseInt(getInput(in, "Enter a base: "));
System.out.println("Int: " + inputInt + ", base: " + inputBase);
}
public static String getInput(Scanner in, String prompt) { // Get valid user input
System.out.print(prompt); // Tell user what to input
String text = "";
while (true) { // Keep looping until valid input is found
text = in.nextLine(); // Get input from stdin
if(isInteger(text)) // Check if they put in integer
break; // Exit loop
System.out.print("Try again, " + prompt); // Wasn't valid, prompt again
}
return text; // Return valid user input
}
private static boolean isInteger(String str) { // Check if string is integer
try {
Integer.parseInt(str); // If this doesn't fail then it's integer
return true;
} catch(NumberFormatException e) {
return false; // Wasn't integer
}
}
Sample run:
Enter an integer: 2 dog five 3
Try again, Enter an integer: 2
Enter a base: cat
Try again, Enter a base: 3
Int: 2, base: 3
It helps to separate functionality - you were trying to read input, validate input, and convert to int all in one method. If you break it up it becomes easier to manage.
Scanner sc= new Scanner(System.in);
String string = sc.findInLine(".{500}"); // length of your input you want
findInLine(String pattern)
method of Scanner class of java.util package. This method returns a String object that satisfies the pattern specified as method argument.
see this article
If you want to only get the first two words (or strings delimited by spaces) you can use the str.split(" "); method.
For example:
String input = in.nextLine(); // Gets the next line the user enters (as a String)
String[] inputWords = input.split(" "); // inputWords[0] is first word, inputWords[1]
// is second word... etc
String validInput = inputWords[0] + " " + inputWords[1]; // Combines the first and
// second words into a string, so if you had "5 five %" validInput would be "5 five"
// inputWords[0] is "5", inputWords[1] is "five", inputWords[3] is "%" etc for any other words...
This will essentially limit the number of inputs to two words. I hope this helps!
Scanner scan = new Scanner(System.in);
System.out.println ("enter a 2 numbers");
String s;
s = scan.nextLine();
Scanner scan2 = new Scanner(s);
int one = scan2.nextInt();
int two = scan2.nextInt();
System.out.println (" int 1 = " + one + " int 2 = " + two);
enter a 2 numbers
23 45 68 96 45
int 1 = 23 int 2 = 45
Process completed.
Very Frustrated at my professor, because she did not teach try and catch concepts, neither did she teach us about throw exceptions either, so it is very difficult for me to do this program. The objective is to make a program where the user is asked to input an integer that prints "Hello World" that many times of the integer. The problem is I cannot check to make sure the user input is an integer. For instance, if the user chose to type a character or a double, how do I implement that into my code? And I cannot use throw exceptions or try and catch because we did not learn them yet.Thanks guys!!!
import java.util.Scanner;
public class PrintHelloWorld
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
number = scan.nextInt();
System.out.print("Your integer is " + number);
int remainder = number%1;
int counts = 0;
if( number>0 && remainder == 0)
{
while(counts <= number)
{
System.out.println("Hello World!");
counts++;
}
}
else
System.out.print("Wrong, choose an integer!");
}
}
scan.hasNextInt()
will check to see if the next value in the input stream is an integer.
as such:
int number = -1;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
if (scan.hasNextInt()) number = scan.nextInt();
if (number != -1) System.out.print("Your integer is " + number);
You can use a loop and validate the input with a regex, like this:
Scanner scan = new Scanner(System.in);
String input = null;
while (true) {
input = scan.nextLine();
if (input.matches("\\d+")) {
break;
}
System.out.println("Invalid input, please enter an integer!");
}
int number = Integer.parseInt(input);
This will keep asking for input until a valid integer is entered.
And I cannot use throw exceptions or try and catch because we did not
learn them yet.
For a first attempt, you could create a method that accepts a String as parameter. You will loop through all the chars of this String and check if each char is a digit. While this method returns false, re-ask the user for a new input.
Then use Integer.valueOf to get the int value..
public static boolean isNumber(String input)
You will have to use sc.nextLine() to get the input
The method Character.isDigit and toCharArray() will be useful