This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 months ago.
I'm doing the Java MOOC fi course. I'm supposed to make a list of show names and durations, and print the ones that are shorten than certain duration.
I want the while loop to end after I enter a blank name but it ends after the first object I add to the list.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// implement here your program that uses the TelevisionProgram class
ArrayList<TelevisionProgram> programs = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Name: ");
String programName = scanner.nextLine();
if (programName.isEmpty()) {
break;
}
System.out.print("Duration: ");
int durationOfProgram = scanner.nextInt();
programs.add(new TelevisionProgram(programName, durationOfProgram));
}
System.out.println();
System.out.print("Program's maximum duration? ");
int maxDuration = scanner.nextInt();
for (TelevisionProgram show : programs) {
if (show.getDuration() <= maxDuration) {
System.out.println(show);
}
}
}
}
replaced
int durationOfProgram = scanner.nextInt();
with
int durationOfProgram = Integer.valueOf(scanner.nextLine());
and now it works but i still don't get why
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed last month.
So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Except {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean bError = true;
int n1 = 0, n2 = 0, nQuotient = 0;
do {
try {
System.out.println("Enter first num: ");
n1 = input.nextInt();
System.out.println("Enter second num: ");
n2 = input.nextInt();
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d",n1,n2, nQuotient);
}
}
If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.
You need to call next(); when you get the error. Also it is advisable to use hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}
Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.
Scanner scanner = new Scanner(System.in);
int n1 = 0, n2 = 0;
boolean bError = true;
while (bError) {
if (scanner.hasNextInt())
n1 = scanner.nextInt();
else {
scanner.next();
continue;
}
if (scanner.hasNextInt())
n2 = scanner.nextInt();
else {
scanner.next();
continue;
}
bError = false;
}
System.out.println(n1);
System.out.println(n2);
Javadoc of Scanner
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.
To follow debobroto das's answer you can also put after
input.reset();
input.next();
I had the same problem and when I tried this. It completely fixed it.
As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.
Try using it this way by using hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.hasNextInt();
}
Or try using nextLine() coupled with Integer.parseInt() for taking input....
Scanner scan = new Scanner(System.in);
int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());
To complement the AmitD answer:
Just copy/pasted your program and had this output:
Error!
Enter first num:
.... infinite times ....
As you can see, the instruction:
n1 = input.nextInt();
Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.
#Limp, your answer is right, just use .nextLine() while reading the input. Sample code:
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.nextLine());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.nextLine());
nQuotient = n1 / n2;
bError = false;
} catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d", n1, n2, nQuotient);
Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread.
Java Homework user input issue
Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.
This question already has answers here:
Make a upside down triangle in java
(3 answers)
Closed 4 years ago.
I'm a beginner in java and I need help with this code. I have to let the user enter a word and the output as follows,(I used Canada as an example)
Canada
anada
nada
ada
da
a
However, I'm not sure what to do. This is what I have so far
import java.util.*;
public class javapdf2413_17 {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter in a single word");
String wordEntered = in.next();
for (int i = wordEntered.length(); i>=0; i--) {
System.out.println(wordEntered.substring (0, i));
}
}
}
This should do it
for (int i = 0; i < wordEntered.length(); i++) {
System.out.println(wordEntered.substring(i));
}
The above substring method takes the beginning index of the string and returns a substring from that index (inclusive) till the end of the string.
You're close. String.substring(1) will return everything from the second character to the end. And I would use that in a loop with test against the empty string. Like,
while (!wordEntered.isEmpty()) {
System.out.println(wordEntered);
wordEntered = wordEntered.substring(1);
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
Below is a program for palindrome. If it is palindrome it will print YES else NO.
I am unable to understand what's the difference in calling:
> int n=Integer.parseInt(in.nextLine());
> or int n=in.nextInt();
because both is doing the same work.
1st one is taking Stringas input then converting it into int
2nd one is taking directly int.
when the 1st one is taken there is no error.
But when 2nd one is taken it gets stored in n then it prints YES.(when debugged i found out that it gets stored in n but it skips the input string str and then it compares with str and s and prints YES).
So can anyone explain the logic behind this.
public class Test1 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//int n=Integer.parseInt(in.nextLine());
int n=in.nextInt();
while(n!=0){
String s="";
String str=in.nextLine();
for(int i=str.length()-1;i>=0;i--){
s=s+str.charAt(i);
}
if(str.equals(s) ){
System.out.println("YES");
}
else{
System.out.println("NO");
}
n--;
}
}
}
I guess that with Scanner you expect the String to be verified... in that case this line int n=in.nextInt(); will throw a java.util.InputMismatchException exception if the input is not a number.
The verification would be easier to achieve by using StringBuilder, like this:
Scanner in=new Scanner(System.in);
String original = in.nextLine();
StringBuilder reversa = new StringBuilder(original).reverse();
if (reversa.toString().equals(original)) {
System.out.println("YES");;
} else {
System.out.println("NO");;
}
This question already has answers here:
Why this giving me 0? [duplicate]
(7 answers)
Closed 8 years ago.
I have written a small program to improve my Java skills. I am trying to get the list of names and print the same using while loop. But the while loop which gets input is not terminating upon reaching the limit. My while condition looks okay. But I'm not sure, what is going wrong. Here is the code:
import java.io.DataInputStream;
import java.io.IOException;
public class MyTestProgram {
public static int count;
public static DataInputStream din;
public static String names[];
public static void main(String[] args) throws NumberFormatException, IOException {
din = new DataInputStream(System.in);
int counter = 0;
System.out.print("Enter the numer of persons: ");
count = Integer.parseInt(din.readLine());
names = new String[count];
System.out.println("Enter the names one by one:");
while (counter < count) {
names[counter] = din.readLine();
counter = counter++;
}
System.out.println("List of names entered:");
while (counter < count) {
System.out.println(names[counter]);
counter = counter++;
}
}
}
For starters, change the way you increament the counter variable.
Just use:
counter++;
Since counter = counter++;, Increments counter, and returns what counter was before the increment, which gets assigned to counter. Here is the explanation.
Also reset your counter variable once first loop is completed.