Trying to grasp exception handling, but I'm not sure I understand just yet. What SHOULD be happening is if the user inputs something other than an integer, the mismatchexception should execute and print that friendly message. Also, on the topic of exception handling, if my code has any useless exceptions in it, let me know (and why if you don't mind). Full code linked below. Thanks!
public static void addRecords() {
System.out.print("Hello, welcome to my magical program!\n");
for (int i = 0; i < 10; i++) {
System.out.printf("Please enter integer no. %d: ", i + 1);
numbers[i] = input.nextInt();
System.out.println();
{
try {
output.format("Inputted integer: %s%n", String.valueOf(numbers[i]));
} catch (FormatterClosedException formatterClosedexception) {
System.err.println("Error writing to the file. Terminating.");
break;
} catch (InputMismatchException inputMismatchException) {
System.err.println("Please restart the program and enter integers ONLY.");
break;
} catch (NoSuchElementException elementException) {
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
}
}
}
Full code here:
http://pastebin.com/eSGau5ax
I would suggest to throw the exception from the methods and catch them in the main method. The methods should not decide what to do with the exceptions, its upto the caller (main method in this case) to decide whether to print it or log it in a file.
Firstly,
java.util.InputMismatchException happens for your data file numbers.txt not containing integer type data. Please input relative data. It will solve this inputmismatchexception.
For your better understanding, follow the tutorial:
https://examples.javacodegeeks.com/java-basics/exceptions/java-util-inputmismatchexception-how-to-solve-inputmismatchexception/
Next,
Use this code. It may help you.
Actually what you have posted in http://pastebin.com/eSGau5ax.
There are 2 errors.
First one error occurred in
try (BufferedReader br = new BufferedReader (new FileReader("numbers.txt"))){
But I changed it like that because there was some error.
try{
BufferedReader br = new BufferedReader (new FileReader("numbers.txt"));
Another error was related to taking input section must be in try catch. But I have not run your code. All credit goes to other SO helpers.
numbers[i] = input.nextInt();
Now your code is looks like
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.nio.file.NoSuchFileException;
public class Average {
private static Formatter output;
static Scanner input = new Scanner(System.in);
static int[] numbers = new int[10];
public static void main(String[] args) {
openFile();
addRecords();
closeFile();
readRecords();
}
public static void openFile() {
try {
output = new Formatter("numbers.txt");
} catch (SecurityException securityException) {
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} catch (FileNotFoundException fileNotFoundException) {
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
public static void addRecords() {
System.out.print("Hello, welcome to my magical program!\n");
try {
for (int i = 0; i < 10; i++) {
System.out.printf("Please enter integer no. %d: ", i + 1);
numbers[i] = input.nextInt();
System.out.println();
output.format("Inputted integer: %s%n", String
.valueOf(numbers[i]));
}
} catch (FormatterClosedException formatterClosedexception) {
System.err.println("Error writing to the file. Terminating.");
break;
} catch (InputMismatchException inputMismatchException) {
System.err
.println("Please restart the program and enter integers ONLY.");
break;
} catch (NoSuchElementException elementException) {
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
}
public static void closeFile() {
{
if (output != null)
output.close();
}
}
public static void readRecords() {
try {
BufferedReader br = new BufferedReader(
new FileReader("numbers.txt"));
String line;
int[] number = new int[10];
int i = -1;
int sum = 0;
double average = 0;
while ((line = br.readLine()) != null) {
i++;
String[] split = line.split(":");
line = split[1].trim();
number[i] = Integer.parseInt(line);
System.out.printf("Integer number %d: %d%n", i, numbers[i]);
sum += number[i];
average = (double) sum / 10;
}
System.out.printf("%nWould your sum happen to be %d? %n", sum);
System.out.printf("Which means your average is: %.2f %n", average);
} catch (NoSuchFileException noSuchFileException) {
System.out
.print("This file was not created properly and cannot be found.");
} catch (FileNotFoundException fileNotFoundException) {
System.out
.print("I can't seem to find your file :( That's too bad...");
} catch (IOException ioexception) {
System.out
.print("Whoopsie daisy, you got yourself an IOException. Better luck next time!");
} finally {
System.out
.print("Check your numbers.txt file and see what ya got!");
}
}
}
You are trying to catch an Exception that happened outside of the try.
Just get the nextInt inside the try
public static void addRecords() {
System.out.print("Hello, welcome to my magical program!\n");
for (int i = 0; i < 10; i++) {
System.out.printf("Please enter integer no. %d: ", i + 1);
System.out.println();
{
try {
numbers[i] = input.nextInt();
output.format("Inputted integer: %s%n", String.valueOf(numbers[i]));
} catch (FormatterClosedException formatterClosedexception) {
System.err.println("Error writing to the file. Terminating.");
break;
} catch (InputMismatchException inputMismatchException) {
System.err.println("Please restart the program and enter integers ONLY.");
break;
} catch (NoSuchElementException elementException) {
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
}
}
}
Related
I wanted to print the multiplication table of a number. So I made a while(true) block to ontinously take inputs from the user. I also made a try and catch block, so that I could handle the exeptions.
Here is my code below :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Getting the multiplication table of any number");
while (true) {
try {
System.out.println();
System.out.print("Enter a number: ");
long number = scanner.nextLong();
for (byte num = 1; num < 11; num++) {
System.out.println(number + "X" + num + " = " + (number * num));
}
System.out.println();
System.out.println();
} catch (Exception e) {
System.out.println("Please enter a valid input.");
}
}
}
}
When I run the programm, it run fine till I introduce just one error. Then it just gives the output:
Enter a number: Please enter a valid input.
Both the statements on the same line, And just continuosly prints the line without any delay or without letting me give it an input.
Why is this happening and how can I correct it?
You can change your catch block as:
catch (Exception e) {
System.out.println("Please enter a valid input.");
scanner.next();
}
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 am learning to handle exception and In try block if i get character input in arr[i] then I want the catch block to ask for array input again.
But the catch block array input code is throwing error.
package Day2;
import java.util.Scanner;
public class LargestinArray {
public static void main(String[] args) {
System.out.println("enter 5 number");
Scanner scanner=new Scanner(System.in);
int arr[]=new int[5];
try{
for (int i=0;i<5;i++){
arr[i]=scanner.nextInt();
}
}catch (Exception e){
System.out.println("error");
for (int i=0;i<5;i++){
arr[i]=scanner.nextInt();
}
}
findLarge(arr);
}
private static void findLarge(int[] arr) {
int max=arr[0],min=arr[0];
for (int i=0;i<arr.length;i++){
if (arr[i]>max){
max=arr[i];
}
if (arr[i]<min){
min=arr[i];
}
}
System.out.println("max is"+max+"min is"+min);
}
}
This is the error i am getting
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Day2.LargestinArray.main(LargestinArray.java:19)
The code below will try reading the scanner input and it'll try again and again until it succeeds reading 5 ints in a row. If you don't necessarily want the correct inputs to be consecutive write a comment below and I'll edit this answer.
boolean isDone = false;
while (!isDone) {
try {
for (int i = 0; i < 5; i++){
arr[i] = scanner.nextInt();
}
isDone = true;
} catch (Exception e){
System.out.println("error");
}
}
Here's a way to read input, looping indefinitely until five consecutive integers are found.
Note that instead of using scanner.nextInt(), I'm using scanner.next(). The reason is that nextInt() will leave unconsumed non-integer input still sitting on the scanner – that is, if there's something non-integer waiting such as a string, that string still be there when you call nextInt() again. You could make scanner.nextInt() work by calling scanner.next() inside the catch block but there might be more to consider about whether that creates any other issues.
private static int[] getNumbers() {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
String next = scanner.next();
numbers[i] = Integer.parseInt(next);
}
return numbers;
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can call the function like this:
int[] numbers = getNumbers();
System.out.println("numbers: " + Arrays.toString(numbers));
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I need help with the following code- essentially what I'm trying to do is continuously prompt user for numbers until they enter "Done" to finish, then prompts the user for a file name so that these values can be saved to that file. For example, if the user enters "output.txt", then the program should write the numbers that have been read to "output.txt".
This is what I have so far:
public static void main(String[] args) {
try{
FileWriter file= new FileWriter("filename.txt");
Scanner input= new Scanner(System.in);
boolean done= false;
do{
System.out.println("Enter a number");
String value= input.nextLine();
if (value.equalsIgnoreCase("done")){
done=true;
Scanner input1= new Scanner(System.in);
System.out.println("What is the filename?");
String filename1= input1.next();
FileWriter finalFile = new FileWriter(filename1);
} else {
try{
double number= Double.parseDouble(value);
file.write(number+ "\n");
file.flush();
}
catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while(!done);
input.close();
file.close();
System.out.println("Success");
}
catch (IOException ioe){
System.out.println(ioe.toString());
}
}
}
the code below outputs two files, one text file (filename.txt) and the other that is appropriately named by the user. How can I fix this? There should only be one output.
Any advice would be much appreciated!
You could...
Store the values been entered by the user in some kind of list. Since the number of values been entered is arbitrary, you'll probably need to use something like an ArrayList, as it provides a dynamic size
Scanner input = new Scanner(System.in);
List<Double> numbers = new ArrayList<Double>(25);
boolean done = false;
do {
System.out.println("Enter a number");
String value = input.nextLine();
done = value.equalsIgnoreCase("done");
if (!done) {
try {
double number = Double.parseDouble(value);
numbers.add(number);
} catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while (!done);
System.out.println("What is the filename?");
String filename1 = input.nextLine();
try (BufferedWriter finalFile = new BufferedWriter(new FileWriter(filename1))) {
for (double number : numbers) {
finalFile.write(Double.toString(number));
finalFile.newLine();
}
} catch (IOException ex) {
ex.printStackTrace();
}
Or you could...
If you're unable to use a List of some kind, you will need to prompt the user for the file name first and then write the values out as they entered...
Scanner input = new Scanner(System.in);
System.out.println("What is the filename?");
String filename1 = input.nextLine();
try (BufferedWriter finalFile = new BufferedWriter(new FileWriter(filename1))) {
boolean done = false;
do {
System.out.println("Enter a number");
String value = input.nextLine();
done = value.equalsIgnoreCase("done");
if (!done) {
try {
double number = Double.parseDouble(value);
finalFile.write(Double.toString(number));
finalFile.newLine();
} catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while (!done);
} catch (IOException ex) {
ex.printStackTrace();
}
What your code does: Create a FileWriter for file "filename.txt" and add the numbers entered by the user. When the user enters done in the command line ask him for the filename and create a new FileWriterfor that file, but dont write anything to it. Then close the first FileWriter.
What you want: Query the user for values, store them somehow, ask for the file location, save the values to the file location.
This should do the job:
try (Scanner input = new Scanner(System.in))
{
List<Double> numbers = new ArrayList<>();
// Query user for numbers.
boolean done = false;
do
{
System.out.println("Enter a number: ");
String value = input.nextLine();
if (value.equalsIgnoreCase("done"))
{
done = true;
}
else
{
try
{
double number = Double.parseDouble(value);
numbers.add(number);
}
catch (NumberFormatException fnfe)
{
System.out.println("Not valid");
}
}
}
while (!done);
// Prompt the user for the file name. If the user just presses enter, reprompt >:-(
String fileName;
do
{
System.out.println("Specify a filename: ");
fileName = input.nextLine();
}
while (fileName.isEmpty());
try (PrintStream ps = new PrintStream(fileName))
{
for (Double number : numbers)
{
ps.print(number);
ps.println();
}
}
System.out.println("Success");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
What I'm trying to do is have this code ask for 2 integer inputs, read data from a file called 'temps.txt', and output the number of days processed, along with the average temperature processed. The problem is I'm getting this error
Input the maximum temperature.
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at TempReader.main(TempReader.java:15)
You did not input a valid integer.
whenever I try to run it. So far my code looks like this:
import java.util.Scanner;
import java.io.File;
public class TempReader{
public static void main(String[] args) throws Exception {
File myFile = new File("temps.txt");
Scanner input = new Scanner(myFile).useDelimiter(",");
while (true){
System.out.println("Input the maximum temperature.");
try {
int maxTemp = input.nextInt();
}
catch (Throwable t) {
t.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = input.nextInt();
}
catch (Throwable t) {
t.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
}
}
}
And the temps txt file looks like this
04/01/2013,10
04/02/2013,20
04/03/2013,30
04/04/2013,40
04/05/2013,50
04/06/2013,60
I've tried using both / and , as delimiters, and neither works, is it possible to have 2 of them, or am I going to have to do something else?
(Yes, I can make it do the processes I mentioned above, all I need help with is this error, as I don't know whats causing it)
Check your data file and what you are trying to read.
04/01/2013 is not an integer!
UPDATE
Use Date d = new SimpleDateFormat("MM/dd/yy").parse(input.next()); to get your date THEN get your temperature with nextInt. Also, you seem to be looking for max AND min temps in the file, but there is only one temp per day. Your attempt to read min temp will always throw an exception because it doesn't exist.
public static void main(String[] args) throws Exception {
File myFile = new File("C:/temps.txt");
Scanner input = new Scanner(myFile);
String linrread = null;
try {
while ((linrread = input.nextLine()) != null) {
System.out.println("linrread ."+ linrread);
if (linrread.indexOf(",") != -1) {
String[] split = linrread.split(",");
String date = split[0];
String temp = split[1];
System.out.println("date :" + date + " temp: " + temp);
}
}
} catch (NoSuchElementException t) {
t.printStackTrace();
System.out.println("Reached end of the file.");
}
}
this code will read your file and get the elements from the file. you have to modify this to fit into your requirement.
I know nothing about Scanner, but I know about the old-fashioned way of doing this, and, more importantly, I know how to make it work. Here's the code:
public class TempReader {
public static void main(String[] args) throws IOException {
File myFile = new File("temps.txt");
BufferedReader input = new BufferedReader(new FileReader(myFile));
String line;
while ((line = input.readLine()) != null) {
StringTokenizer tok = new StringTokenizer(line, ",");
System.out.println("Input the maximum temperature.");
try {
int maxTemp = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
}
}
}
This is a straightforward modification of your program, with BufferedReader, StringTokenizer, and Integer.parseInt used in place of Scanner, which I could never understand that well.