Is there an equivalent of while(scanf()==1) in java? - java

I have been using the following code in c and c++ for looping till user feeds the correct value till the program comes out of it:
while((scanf("%d",&num)==1)//same way in for loop
{
//some code
}
Can i some how use the same way to accept and loop the program till i keep entering let's say an integer and floating or a char or a special character breaks it.

Use :
Scanner sc = new Scanner(System.in); // OR replace System.in with file to read
while(sc.hasNext()){
//code here
int x = sc.nextInt();
//...
}
There are different variants of hasNext() for specific expected input types: hasNextFloat(), hasNextInt()..
Same goes for next() method so you can find nextInt(), nextFloat() or even nextLine()
You can go to Java doc for more info.

As proposed in comments, you can use the Scanner class.
Note you need to read the in buffer with a nextLine() when it is not an int.
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter an int: ");
while (!in.hasNextInt()) {
System.out.println("That's not an int! try again...");
in.nextLine();
}
int myInt = in.nextInt();
System.out.println("You entered "+myInt);
}
}

Related

Try Catch Exception stuck repeating in any while loop (Java) [duplicate]

This is the program
public class bInputMismathcExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.println("Enter an integer:");
int num = input.nextInt();
System.out.println("the number is " + num);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (Incorrect input: an integer is required)");
}
input.nextLine();
}
while (continueInput);
}
}
I know nextInt() only read the integer not the "\n", but why should we need the input.nextLine() to read the "\n"? is it necessary?? because I think even without input.nextLine(), after it goes back to try {}, the input.nextInt() can still read the next integer I type, but in fact it is a infinite loop.
I still don't know the logic behind it, hope someone can help me.
The reason it is necessary here is because of what happens when the input fails.
For example, try removing the input.nextLine() part, run the program again, and when it asks for input, enter abc and press Return
The result will be an infinite loop. Why?
Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared. It will still be abc in the buffer. So going back to the loop will cause it to try parsing the same abc over and over.
Using nextLine() will clear the buffer, so that the next input you read after an error is going to be the fresh input that's after the bad line you have entered.
but why should we need the input.nextLine() to read the "\n"? is it necessary??
Yes (actually it's very common to do that), otherwise how will you consume the remaining \n? If you don't want to use nextLine to consume the left \n, use a different scanner object (I don't recommend this):
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
input1.nextInt();
input2.nextLine();
or use nextLine to read the integer value and convert it to int later so you won't have to consume the new line character later.
Also you can use:
input.nextInt();
input.skip("\\W*").nextLine();
or
input.skip("\n").nextLine();
if you need whitespaces before line

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);

Scanner code that produces an error message instead of crashing

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());
}

How does input.nextInt() work exactly?

This is the program
public class bInputMismathcExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.println("Enter an integer:");
int num = input.nextInt();
System.out.println("the number is " + num);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (Incorrect input: an integer is required)");
}
input.nextLine();
}
while (continueInput);
}
}
I know nextInt() only read the integer not the "\n", but why should we need the input.nextLine() to read the "\n"? is it necessary?? because I think even without input.nextLine(), after it goes back to try {}, the input.nextInt() can still read the next integer I type, but in fact it is a infinite loop.
I still don't know the logic behind it, hope someone can help me.
The reason it is necessary here is because of what happens when the input fails.
For example, try removing the input.nextLine() part, run the program again, and when it asks for input, enter abc and press Return
The result will be an infinite loop. Why?
Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared. It will still be abc in the buffer. So going back to the loop will cause it to try parsing the same abc over and over.
Using nextLine() will clear the buffer, so that the next input you read after an error is going to be the fresh input that's after the bad line you have entered.
but why should we need the input.nextLine() to read the "\n"? is it necessary??
Yes (actually it's very common to do that), otherwise how will you consume the remaining \n? If you don't want to use nextLine to consume the left \n, use a different scanner object (I don't recommend this):
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
input1.nextInt();
input2.nextLine();
or use nextLine to read the integer value and convert it to int later so you won't have to consume the new line character later.
Also you can use:
input.nextInt();
input.skip("\\W*").nextLine();
or
input.skip("\n").nextLine();
if you need whitespaces before line

how to accept multiple lines of input just once and making sure the user is not asked for input once again

I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}

Categories