NumberFormatException for 2 textfields java - java

I was wondering how you would go about outputting which of the two text boxes is holding the NumberFormatException.
try
{
num1Convert = Integer.parseInt(num1Str);
num2Convert = Integer.parseInt(num2Str);
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
}
catch(NumberFormatException nfe)
{
errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer");
num1.requestFocus();
}
my program compares two numbers, and then returns the value of the numbers added together, but I need to output which of the two textareas are throwing back the exception, but I don't know how to do this. I have wrote within the code where it is necessary to output it.

How about this :
try{
num1Convert = Integer.parseInt(num1Str);
}
catch(NumberFormatException nfe) {
System.out.println("Exception in num1");
}
try{
num2Convert = Integer.parseInt(num2Str);
} catch(NumberFormatException nfe) {
System.out.println("Exception in num2");
}
//EDIT
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));

Something like this should do:
String currentString = "";
try
{
currentString = num1Str;
num1Convert = Integer.parseInt(num1Str);
currentString = num2Str;
num2Convert = Integer.parseInt(num2Str);
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
}
catch(NumberFormatException nfe)
{
// errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer");
errorLabel.setText(currentString + " must be an integer");
num1.requestFocus();
}

Related

Retrieve lines in txt file and append new inputs from the user java

I'm using an arraylist to append inputs and send the arraylist elements to file. However, everytime I exit the program and run it again, the contents in the written in the file becomes empty.
ArrayList<String> memory = new ArrayList<String>();
public void fileHandling() {
try {
FileWriter fWriter = new FileWriter("notes.data");
for (int x = 0; x <= memory.size() - 1; x++) {
fWriter.write(memory.get(x) + '\n');
}
fWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
public void createNote() {
Scanner insertNote = new Scanner(System.in);
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;
while (true) {
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = insertNote.nextLine();
if (note == null) {
System.out.println("Invalid input! Try again");
break;
} else {
memory.add(note + " /" + dateTime);
fileHandling();
System.out.println("Note is saved!\n");
break;
}
}
I expect the program to save the contents of every input. Then if I exit and run the program again, the contents will go back to the array
Your code currently does the following:
You enter something (X) for the first time:
It gets added to the ArrayList
The ArrayList gets written into the file
Your file now contains: X
You enter something second (Y):
It gets added to the ArrayList (Which now contains: X, Y)
The ArrayList gets written into the file
Your file now contains: X + newline + Y
Your Problem is, that everytime you create a new FileWrite it overwrites your file.
This can be avoided by using the constructor like this:
FileWriter writer = new FileWriter("notes.data", true);
This sets it into the append mode and therefore keeps previous data in the file
You don't need to create a separate Scanner, in method createNote(), in order to get a "note" from the user.
It is usually better to write your code using the interface rather than the specific implementation because then you usually need to change less code if you decide to change the implementation. Hence the type for member variable memory should probably be List rather than ArrayList.
Note that ArrayList may waste memory if the list of "note"s is large. I suggest using LinkedList instead. Alternatively, use an array (rather than a List) and handle expanding the array when adding a "note" as well as reducing the array when removing a "note".
Having an infinite loop, i.e. while (true), which contains a single if-else where both the if block and the else block contain break statements, means that the loop will perform exactly one iteration. May as well remove the while loop – which means also removing the break statements.
Rather than writing the code that generates a timestamp repeatedly, you should adopt the DRY principle and extract that code into a separate method.
The file name should be a constant so as to minimize the amount of code changes you will need to do if you decide to change the file name.
By convention, text files have a filename extension of .txt whereas binary files have the .data extension.
Although you don't need to, I personally prefer to initialize class member variables in the constructor.
The below code is a SSCCE, hence I added a main method. More notes appear after the code.
package Methods;
import java.util.*;
import java.time.format.*;
import java.time.*;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileSys {
private static final String FILENAME = "notes.txt";
private static final String CREATE = "C";
private static final String DELETE = "D";
private static final String FIND = "F";
private static final String QUIT = "Q";
private static final String SHOW = "S";
private static final String UPDATE = "U";
Scanner reader;
List<String> memory;
public FileSys() throws IOException {
reader = new Scanner(System.in);
memory = new LinkedList<String>();
loadFile();
}
public void fileHandling() {
Path path = Paths.get(FILENAME);
try (BufferedWriter bw = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
PrintWriter pw = new PrintWriter(bw)) {
for (String write : memory) {
pw.println(write);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public void createNote() {
String dateTime = getTimestamp();
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = reader.nextLine();
memory.add(note + " / " + dateTime);
fileHandling();
System.out.println("Note is saved!");
}
public void searchNote() {
System.out.print("\nEnter note number: ");
try {
int search = reader.nextInt();
reader.nextLine();
System.out.println("\nSearch result:");
int index = memory.indexOf(memory.get(search - 1));
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
}
else {
System.out.println("Note number-" + search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
}
public void updateNote() {
String dateTime = getTimestamp(); // ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
System.out.print("\nEnter note number to change: ");
try {
int search = reader.nextInt();
int index = memory.indexOf(memory.get(search - 1));
String updateLine;
if (index != -1) {
System.out.println("\nCurrent note: ");
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.println("\nThe updated note will be: ");
System.out.print("> ");
reader.nextLine();
updateLine = reader.nextLine();
memory.set(index, updateLine + " /" + dateTime);
System.out.print("Note has been updated successfully!\n");
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void deleteNote() {
System.out.print("\nEnter note number to delete: ");
try {
int search = reader.nextInt();
reader.nextLine();
int index = memory.indexOf(memory.get(search - 1));
System.out.println();
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.print("\nDo you want to delete this note? \n[y] or [n]: ");
char delDecision = reader.nextLine().charAt(0);
if (delDecision == 'y' || delDecision == 'Y') {
memory.remove(index);
System.out.println("Note has been deleted successfully!");
System.out.println();
}
else if (delDecision == 'n' || delDecision == 'N') {
System.out.println("Note was not deleted!");
}
else {
System.out.println("Invalid input!");
}
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void displayNote() {
if (memory.size() > 0) {
int counter = 0;
for (String note : memory) {
System.out.printf("%d. %s%n", ++counter, note);
}
}
else {
System.out.println("There are no notes.");
}
}
private String getTimestamp() {
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;// ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
return dateTime;
}
private void loadFile() throws IOException {
Path path = Paths.get(FILENAME);
if (Files.isRegularFile(path)) {
memory.addAll(Files.readAllLines(path, Charset.defaultCharset()));
}
}
private void showMenu() {
String choice = "";
while (!QUIT.equalsIgnoreCase(choice)) {
System.out.println(CREATE + " - Create note");
System.out.println(DELETE + " - Delete note");
System.out.println(FIND + " - Search notes");
System.out.println(SHOW + " - Show notes");
System.out.println(UPDATE + " - Update note");
System.out.println(QUIT + " - Quit");
System.out.println();
System.out.print("Your choice: ");
choice = reader.nextLine();
if (!choice.isEmpty()) {
choice = choice.substring(0, 1);
choice = choice.toUpperCase();
switch (choice) {
case CREATE -> createNote();
case DELETE -> deleteNote();
case FIND -> searchNote();
case SHOW -> displayNote();
case UPDATE -> updateNote();
case QUIT -> System.out.println("Good bye.");
default -> System.out.println("Invalid: " + choice);
}
}
else {
System.out.println("No selection entered. Retry.");
}
}
}
public static void main(String[] args) {
try {
FileSys fs = new FileSys();
fs.showMenu();
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Your code does not initially load memory with contents of file notes.txt so I added that in the constructor. Consequently you don't need to append to the file since you simply overwrite it with contents of memory.
The file handling is done using NIO.2 including try-with-resources – which was added in Java 7. There are more NIO.2 examples in the JDK documentation.
Whenever the code throws an unexpected exception, it is nearly always a good idea to print the stack trace.

How to add the bonus?

I have done a code, which reads a file consists a number of employees, salary, and their rankings, based on their rankings how can we add the bonus percent to their salary...
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
double bonus;
if(phrases.contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
It outputs:
Jame 900000 1
Bonus: 0.0
Jane 60000 2
Bonus: 0.0
Don 866000 3
Bonus: 0.0
I have no idea why
If you have an employeeBonus.txt file like below.
Jame 900000 2
Jane 60000 1
Don 866000 3
I think you will have three tokens as a string so, you can use a stringtokenizer class in order to get a salary and a grade.
At the first line of file is
Jame 900000 2
and the result of encoded string was
Jame%20%20%20%20900000%092
I've finally found the content of text file was mixed with a space and tab character by URL encoding.
So, the usage of this type is as follows,
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
It takes a salary and an identifier of bonus value from third and second token.
name = stTok.nextToken(); //first token
salary = Integer.valueOf(stTok.nextToken()).intValue(); //second token
grade = stTok.nextToken();
[source code]
package com.tobee.tests.inout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class CheckBounsFromFile {
public static void main(String[] args) {
String name, phrase, grade;
double bonus = 0;
int salary = 0;
BufferedReader readFile = null;
try {
readFile = new BufferedReader(new FileReader("resource/aa/employeeBonus.txt"));
while ((phrase = readFile.readLine()) != null) {
//System.out.println(phrase);
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
name = stTok.nextToken();
salary = Integer.valueOf(stTok.nextToken()).intValue();
grade = stTok.nextToken();
if(grade!= null && !grade.equals(""))
{
if (grade.equals("1")) {
bonus = salary / 0.03;
} else if (grade.equals("2")) {
bonus = salary / 0.08;
} else if (grade.equals("3")) {
bonus = salary / 0.20;
}
System.out.printf("name[%s]salary[%d]Bonus[%f] \n",name, salary, bonus);
}
}
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
finally
{
try {
readFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
[result]
name[Jame]salary[900000]Bonus[30000000.000000]
name[Jane]salary[60000]Bonus[750000.000000]
name[Don]salary[866000]Bonus[4330000.000000]
Have a nice day.
The other answers appear to not cater for the fact that your salary variable is always 0, thus, your bonus calculation, which depends on your salary value will always be 0.
Assuming that this: Jame 900000 1 is a sample line from your text file, there are various issues with your code.
The first issue is this: (phrases.equals("1"). If phrase will be equal to the text in the current line you are processing: Jame 900000 1, this statement (and the same for the other two) will never return true, thus the bonus will never be calculated.
The second issue is that you are never extracting the salary value.
You will need to replace this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
if(phrases.equals("1")){
With something like this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
String[] employeeData = phrases.split("\\t"); //This assumes that your data is split by tabs.
salary = Double.parse(employeeData[1]);
if("1".equals(employeeData[2])) {
bonus = salary * 0.03;
}
...
You check the condition with equals method but your phrases variable contains different value rather than 1,2,3 that's why you get the bonus 0.
if(phrases.contains("1")){
bonus=salary/0.03;
}else if(phrases.contains("2")){
bonus=salary/0.08;
}else if(phrases.contains("3")){
bonus=salary/0.20;
}
or you can get the last parameter with:
phrases.substring(phrases.length()-1, phrases.length())
you can get the third parameter using contains or split method.
Please check this tutorial: https://www.tutorialspoint.com/java/java_string_split.htm
And one more thing your salary is always zero (0). please correct it
I have posted full code here:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class SubClass{
public static void main(String[] args) {
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
phrases = phrases.trim().replaceAll("[ ]{2,}", " ");
String splitStr [] = phrases.split(" ");
double bonus;
salary = Integer.parseInt(splitStr[1]);
if(splitStr[2].contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}

Retrieve saved data from a text file but only show a portion of the data Java JGrasp

I have programmed a game were I have made it so that you can save your score, if you have a good score you will be in the top 10. My problem is when I retrieve the data with the saved names, I only want a proportion of that data to be shown, in this case 10 names.
Here is my code.
public static void Highscore(List<Highscore> data) {
String HighscoreList = "";
try {
//Textfilens name
String filname = "Highscore.txt";
Scanner inFil = new Scanner(new File(filname));
while(inFil.hasNext()) {
String name = inFil.next();
String percent = inFil.next();
HighscoreLista += name + "\n" + percent + "%" + "\n\n";
} inFil.close();
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(null,"File was not found!");
}
JOptionPane.showMessageDialog(null, HighscoreList);
}//Highscore ends
How do I only show a proportion of the players in the final message (Highscorelist).
Thank you for helping.
Create a counter variable in the function to track the number of items in the while loop and check the counter variable along with the while condition
public static void Highscore(List<Highscore> data) {
String HighscoreList = "";
int counter =0;
try {
//Textfilens name
String filname = "Highscore.txt";
Scanner inFil = new Scanner(new File(filname));
while(inFil.hasNext() && counter<=10) {
counter++;
String name = inFil.next();
String percent = inFil.next();
HighscoreLista += name + "\n" + percent + "%" + "\n\n";
} inFil.close();
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(null,"File was not found!");
}
JOptionPane.showMessageDialog(null, HighscoreList);
}//Highscore ends

Java compressing try/catch codes exceptions

Is there any way to compress the try/catch block codes? Right now, my code has a try/catch code inside a try/catch code.
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
try {
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
}
You could do this
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
}
Or with Java 7
try {
...
} catch(ParseException | NoSuchElementException ex) {
...
}
If that's what you meant by compression.
1st of all, a single try block can be followed by a series of catch blocks:
try {
throw IOException("msg");
...
throw InterruptedException("msg");
}
catch (IOException ioe){
...
} catch (InterruptedException ie) {
...
}
This is not the best practice, because you might want to narrow your try/catch blocks to handle smaller content of code regarding the Exceptions
You can only use one try block, and then use catch(Exception ex) to catch all those exceptions. If you want to react to the specific kind of exception, you have to test for it.
You can do it (see below). But you might want to think about the structure of your code, for example, maybe you can restructure so that you don't have to call input.nextLine in each catch block.
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
}
Personally, I don't like nesting try/catch blocks. I wouldn't write it this way; I'd prefer it more like this:
if(petType.equals("DOG")) {
String vaccineDateString;
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
DateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
stdDate.setLenient(false);
vaccineDateString = input.next();
Date vaccineDate = stdDate.parse(vaccineDateString);
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
} catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + vaccineDateString + " is not in MM/dd/yy format!");
input.nextLine();
} catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
}
I would also look askance at your mingling input with all this other stuff. I'd find another way.

Try/catch in Java

Could someone please give me a hint why this try and catch is not working?
It throws a scanner exception instead of printing the message I expect.
import java.util.*;
import java.io.*;
import java.math.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
Boolean test = true;
while (test == true) {
try {
double x, y;
String operator;
Scanner scan = new Scanner(System.in);
Scanner scan_2 = new Scanner(System.in);
Scanner ScanOperator = new Scanner(System.in);
System.out.println(" Enter a double value: ");
x = scan.nextDouble();
System.out.println(" Enter another double value: ");
y = scan_2.nextDouble();
System.out.println(" Enter a operator for the operation you want to execute, or X if you want to quit: ");
operator = ScanOperator.nextLine();
if (operator.equals("x") || operator.equals("X")) {
test = false;
System.out.println("No calculation was made!!!");
}
System.out.println(Calculation(operator, x, y));
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
}
}
public static double Calculation(String operator, double x, double y) {
double result = 0;
double myAdd = 0;
double mySub = 0;
double myMult = 0;
double myDiv = 0;
double myPower = 0;
double myMod = 0;
if (operator.equals("+")) {
myAdd = x + y;
result = myAdd;
} else if (operator.equals("-")) {
mySub = x - y;
result = mySub;
} else if (operator.equals("*")) {
myMult = x * y;
result = myMult;
} else if (operator.equals("/")) {
myDiv = x / y;
result = myDiv;
} else if (operator.equals("^")) {
myPower = Math.pow(x, y);
result = myPower;
} else if (operator.equals("%")) {
myMod = x % y;
result = myMod;
} else {
}
return result;
}
}
Simple, the program throws ScannerException, but your try catch can only catch NumberFormatException, you need to add another catch clause in order to catch ScannerException, or catch only the generic Exception.
for example, when you say:
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
that is only specifying how to catch NumberFormatException.
In order to catch all exceptions, you would need to make it:
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}catch (Exception e){
JOptionPane.showMessageDialog(null,"Generic exception caught");
}
In this case, the second catch would get everything that was not caught in the first catch because all exceptions extend the Exception class, you can catch all derived classes with that statement.
However, since catching Exception by itself is frowned upon, you could also do:
} catch (NumberFormatException, ScannerException e) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
To catch both exceptions in the same block.
You're attempting to catch a NumberFormatException. You need to add a catch statement for a ScannerException, as it is different from a NumberFormatException.
You need to catch a ScannerException or some like this.
At this code you are only catching the NumberFormatException .
Try some like this:
try {
...
} catch (NumberFormatException, ScannerException exception) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
You're catching the wrong exception.
Your code will not throw a NumberFormatException. You should catch an InputMismatchException instead.
Looking at nextDouble, in Scanner, it seems that the Scanner code handles the NumberFormatException for you and then throws a different type of exception:
from java.util.Scanner:
public double nextDouble() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Double)) {
double val = ((Double)typeCache).doubleValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
return Double.parseDouble(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
When you hit a problem like this, I recommend that you look through the Java source as a first stop. It is a great resource.
Also note that there is no ScannerException in the JDK.
Just catch InputMismatchException instead of NumberFormatException and everything works fine.
Why not just do:
String input = scan.nextLine();
if(!input.matches("\\d+")) { // regex for 1 or more digits
System.err.println("Input must be at least 1 digit!");
continue; // goes back to the top of the loop
}
double dbl = Double.valueOf(input);
FYI, the actual regex for double precision would be [digit][.][digit] with the [.][digit] being optional.

Categories

Resources