I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.
Java newbie here... I want to scan some user input after a button is pressed. The first thing that I scan from keyboard works fine but in the second input the programm crashes. I believe the problem is with the second use of try{//blocks of code}finally{input. close();} (same code though). I used it so I can get out of the scanning process. I need your sights. Thx for the help. Here is my code:
#Override
public void action Performed(Action Event e) {
if(e.getSource()==button1){
System.out.println("Sth");
label1.setVisible(true);
Scanner input = new Scanner(System.in);
try {
String userInput = "";
System.out.println("Asking the user a q, (yes/no)");
userInput = input.nextLine();
if(userInput.equalsIgnoreCase("yes")) {
System.out.println("Okay");
int Temp = input.nextInt();
System.out.println("Print the scanned value");
input.close();
}else if(userInput.equalsIgnoreCase("no")) {
System.out.println("Default answer to q");
}
}finally{
input.close();
}
} else if(e.getSource()==button2){
System.out.println("Sth");
label2.setVisible(true);
Scanner input = new Scanner(System.in);
try {
String userInput = "";
System.out.println("Q for user, (yes/no)");
userInput = input.nextLine();
if(userInput.equalsIgnoreCase("yes")) {
System.out.println("Sth");
int Time = input.nextInt();
System.out.println("" + Time + "");
input.close();
}else if(userInput.equalsIgnoreCase("no")) {
System.out.println("Okay");
}
}finally{
input.close();
}
}
}
I want to ask the user to enter a String, and four integer values, and i want the program to keep asking the user for integer value if the user input a type mismatch, why the code keep looping forever and never wait for the user input if the user inserted a wrong type ?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv, breakInterv, terminalBreakInterv;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
while (true) {
try {
System.out.println("Please, Enter the Pomodoro interval: ");
pomoInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
while (true) {
try {
System.out.println("Please, Enter the break interval: ");
breakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
while (true){
try {
System.out.println("Please, Enter the terminal break interval ");
terminalBreakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
}
}
According to scanner oracle docs :
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
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.
So when you entered anything other than an integer, the scanner.nextInt() will not parse it to integer and throw InputMismatchException and the scanner will not move to the next token and tried to read again and again the same token.
To solve this, you can either change the loop or use hasNextInt() method or use scanner.next() in the catch block so that the scanner can move to the next token.
I always use do-while loop when checking for correct Input from the user.
See if the following works:
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv = -1, breakInterv = -1, terminalBreakInterv = -1;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
boolean isPomoInterv = false;
do {
System.out.println("Please, Enter the Pomodoro interval: ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
pomoInterv = Integer.parseInt(temp);
isPomoInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isPomoInterv);
boolean isBreakInterv = false;
do {
System.out.println("Please, Enter the break interval: ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
breakInterv = Integer.parseInt(temp);
isBreakInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isBreakInterv);
boolean isTerminalBreakInterv = false;
do {
System.out.println("Please, Enter the terminal break interval ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
terminalBreakInterv = Integer.parseInt(temp);
isTerminalBreakInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isTerminalBreakInterv);
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
The comment on your question by scary-wombat is correct. i have used his comment to code the above.
I actually solved it, i just had to add a (scanner.next();) in the catch statement as below, it's because how the Scanner class works, see the code below,
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv, breakInterv, terminalBreakInterv;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
while (true) {
try {
System.out.println("Please, Enter the Pomodoro interval: ");
pomoInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
while (true) {
try {
System.out.println("Please, Enter the break interval: ");
breakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
while (true){
try {
System.out.println("Please, Enter the terminal break interval ");
terminalBreakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
}
}
check this answer
https://stackoverflow.com/a/47852703/12565862
Because you don't have a break; in catch block. When there is exception, you print the message. But once it comes out of catch block, while loop still satisfies its condition and execute again. Try adding break; inside catch block too.
I have this application which prompts the user for a text file for input, from this text file, it contains strings of integers and text. And from there, it supposed to write to another text file, result.txt. Right now, as I'm still new to IO I am having problems with writing to the file although the file successfully created. The application stops right at the part after the user inputs the text file's name. So could you guys give me some help on that please? Thanks in advance!
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do
{
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if(a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch(FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
}while(fileInput == null);
PrintWriter output = null;
try
{
output = new PrintWriter(new File("result.txt"));
}
catch(IOException g)
{
System.out.println("Error");
System.exit(0);
}
while(fileInput.hasNext())
{
if(fileInput.hasNextInt())
{
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
}
}
fileInput.close();
output.close();
}
}
It is stuck because you have to call the next() method after calling hasNext()so the pointer goes to next line of your input file.
Also you are not using sum so check if you need this variable.
Here is the code that works:
public static void main(String[] args) throws FileNotFoundException {
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do {
try {
System.out
.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if (a.equals("QUIT")) {
System.exit(0);
}
fileInput = new Scanner(new File(a));
} catch (FileNotFoundException e) {
System.out.println("Error " + a + " does not exist.");
}
} while (fileInput == null);
PrintWriter output = null;
try {
output = new PrintWriter(new File("result.txt"));
} catch (IOException g) {
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext()) {
if (fileInput.hasNextInt()) {
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
} else {
fileInput.next();
}
}
fileInput.close();
output.close();
}
}
Update:
As per java doc for 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.
So to go to the next position, you need to call the next() method, otherwise the Scanner will be at same position and the program gets stuck in infinite loop.
I'm trying to use a try{} catch{} to get a correct file input from the user, however I don't know how to keep asking for input until I get a valid file. I can't use an if statement, this is what I have so far. The file is filled with integers, and it applies to another method. I have FileReader to make sure the file exists, if it doesn't it should throw an exception.
public static int readFilename() {
Scanner scan = new Scanner(System.in);
String input;
int average = 0;
try{
System.out.print("Enter a filename: ");
input = scan.next();
FileReader read = new FileReader(input);
average = AverageFile.average(input);
}
catch(FileNotFoundException e){
System.out.println("Incorrect file input");
}
return average;
}
try this
public static int readFilename() {
Scanner scan = new Scanner(System.in);
String input;
int average = 0;
boolean flag= true;
while(flag)
{
try{
System.out.print("Enter a filename: ");
input = scan.next();
FileReader read = new FileReader(input);
average = AverageFile.average(input);
flag= false;
}
catch(FileNotFoundException e){
System.out.println("Incorrect file input");
}
}
return average;
}