Java NumberFormatException - java

#MadProgrammer, I have used the NumberFormatException to capture blanks or characters and throw back a warning message. It was successful for the main page but for the option, "add t", instead of display each t-shirt color it loops around the first color, blue. I have also tried 'while' loop statement but it causes the program to stop. If it worked for the first part, display_menu(), I don't understand why it doesn't work for "add_t".
import javax.swing.JOptionPane;
public class OnlineStore {
String[] ColorType = { "blue", "green", "black" };
final int COLOURS = 3; // t choices
int[] Color = new int[COLOURS];
int sum;
public int display_menu(){ // Not the main program but the main menu.
String input = null;
boolean test = true;
while (test == true) {
try {
input = JOptionPane.showInputDialog("Welcome!" + "\n\n1. Add t order\n2. Edit t order\n3. View current order\n4. Checkout" + "\n\nPlease enter your choice: ");
return Integer.parseInt(input);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
}
return Integer.parseInt(input);
}
public OnlineStore(){ // Switch-case program
boolean exit = false;
do {
switch (display_menu()) {
case 1:
add_t();
break;
case 2:
exit = true;
break;
default: // If an error is encountered.
JOptionPane.showMessageDialog(null, "Oh dear! Error!");
break;
}
} while (!exit);
}
public final int add_t() {
for (int index = 0; index < ColorType.length; index++) {
boolean test = true;
while (test == true) {
try {
String orderItems = JOptionPane.showInputDialog("Please enter your t order for " + ColorType[index]);
int items = Integer.parseInt(orderItems);
Color[index] = items;
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
}
}
sum = Color[0] + Color[1] + Color[2];
JOptionPane.showMessageDialog(null, "Your total order is " + sum);
return Color.length;
}
public static void main(String[] args){ // Main program
new OnlineStore(); // Call out the program.
}
}

Let's have a quick look at add_t...
public final int add_t() {
for (int index = 0; index < ColorType.length; index++) {
boolean test = true;
while (test == true) {
try {
String orderItems = JOptionPane.showInputDialog("Please enter your t order for " + ColorType[index]);
int items = Integer.parseInt(orderItems);
Color[index] = items;
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
}
}
sum = Color[0] + Color[1] + Color[2];
JOptionPane.showMessageDialog(null, "Your total order is " + sum);
return Color.length;
}
First, you have a for-loop so you can prompt for each color type, not unreasonable, next you have while (test == true), now, having a quick loop inside the loop, there's no exit condition, no where do you set test to false so the loop can exit...opps, infinite loop.
The reason it works in your previous attempt is, if no error is generated by Integer.parseInt, the value is automatically returned
return Integer.parseInt(input);
Now, I'm old school, I like one entry point and one exit from a method, it prevents mistakes or misunderstandings like this one.
Instead, since this seems like something you might do a lot, I'd write a simple "prompt for a integer" method, something like...
public Integer promptForInt(String prompt) {
Integer value = null;
boolean exit = false;
do {
String input = JOptionPane.showInputDialog(prompt);
if (input != null) {
try {
value = Integer.parseInt(input);
} catch (NumberFormatException exp) {
JOptionPane.showMessageDialog(null, "Input must be a number.");
}
} else {
exit = true;
}
} while (value == null && !exit);
return value;
}
Now, all this does is asks the user for int value. It will keep looping until the user either enters a valid int value or presses cancel. The method will either return a int (Integer to be exact) or a null. The null indicating that the user pressed the cancel button
Now, you can simply use
public int display_menu() // Not the main program but the main menu.
{
Integer value = promptForInt("Welcome!" + "\n\n1. Add t order\n2. Edit t order\n3. View current order\n4. Checkout" + "\n\nPlease enter your choice: ");
return value != null ? value : 4;
}
and
public final int add_t() {
boolean canceled = false;
for (int index = 0; index < ColorType.length; index++) {
Integer value = promptForInt("Please enter your t order for " + ColorType[index]);
if (value != null) {
Color[index] = value;
} else {
canceled = true;
break;
}
}
if (!canceled) {
sum = Color[0] + Color[1] + Color[2];
JOptionPane.showMessageDialog(null, "Your total order is " + sum);
}
return canceled ? -1 : Color.length;
}
to ask for int values from the user

Related

Program won't continue when pressing enter. How do I fix this error?

I am working on a rock paper scissors homework assignment for my java class. I am done with the program and I compiled it successfully. I ran the file and it looked like it was working. It gives me the menu and I choose a variable, R for example, and when I press enter it doesn't do anything but go to the next line. I press enter again and it gives me an index out of bounds error which I assume is because the second time it didn't have a variable to use. How do I get the program to move forward? The program is supposed to play five times then return a winner. Thanks in advance.This image is what I get when I run the program and press enter twice
package Rock;
import java.util.Scanner;
public class RPSG {
public static void main(String[] args) {
String[] computerHandArray = {"R","P","S"};
String computerHand ="", thisWinner="", theFinalWinner="";
int index=0;
int timesIWon=0;
int timesComputerWon=0;
Scanner in = new Scanner(System.in);
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\nEnter Your Hand (R, P, or S): ");
for (int i=0; i<5; i++) {
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
}
else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
}
}
if(timesIWon == timesComputerWon)
theFinalWinner = "TIE";
else if(timesIWon > timesComputerWon)
theFinalWinner = "ME";
else if(timesComputerWon > timesIWon)
theFinalWinner = "COMPUTER";
System.out.println("I won :" + timesIWon);
System.out.println("I won :" + timesComputerWon);
System.out.println("The Final Winner after 5 games is:" +theFinalWinner);
}
private static String theWinnerofOneGame(String myHand, String computerHand){
String theWinner = "Tie";
if(myHand.equals(computerHand)) {
theWinner = "Tie";
}
else if(myHand.equals("R")) {
if (computerHand.equals("P")) {
theWinner = "COMPUTER";
}
}
else if(computerHand.equals("S")) {
theWinner = "ME";
}
else if(myHand.equals("P")) {
if (computerHand.equals("R")) {
theWinner = "ME";
}
else if(computerHand.equals("S")) {
theWinner = "COMPUTER";
}
}
else if(myHand.equals("S")) {
if (computerHand.equals("R")) {
theWinner = "COMPUTER";
}
else if(computerHand.equals("P")) {
theWinner = "ME";
}
}
return theWinner;
}
}
You print the prompt for input only once, i.e. before the for loop. Now when you enter your first input, the content of the loop will be executed. Because you don't print anything inside the loop, there is no prompt for the next round. After you press enter a second time, the in.nextLine() returns an empty string and subsequently, the substring method throws the exception.
You should probably do something like this (note the marked lines):
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\n");
for (int i=0; i<5; i++) {
> System.out.println("Enter Your Hand (R, P, or S): ");
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
> System.out.println("You won.");
} else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
> System.out.println("The computer won.");
}
}
And even better, check if the input of the user is valid before computing the substring.

Appropriate InputOutput

Good day, i'm stuck figuring out correct way to implement a function, the function has the following functionality.
1. When program starts, text is displayed to enter a key or leave field empty.
2. If text was entered , do A.
3. If text wasn't entered do B.
This is what i've done so far.
System.out.println("Enter any key to get data or leave empty");
//Just give some value
int value = 0;
try {
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000);
//If enter was pressed then theoretically value
//should be 1(Not working)
value = System.in.read();
}
if (value != 0) {
Database.getInstance().getAllStamps();
} else {
start();
}
} catch (Exception e) {
e.printStackTrace();
}
Scanner sc = new Scanner(System.in);
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000); // Execution pauses
if(sc.hasNext())
// call your function
break;
}
}
or
boolean flag = false;
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
Thread.sleep(1000); // Execution pauses
if(sc.hasNext())
flag = true;
}
}
if(flag) {
// call your function
}
One way to get raw input is to use a java.util.Scanner.
Use something like this:
Scanner sc = new Scanner(System.in);
if(sc.hasNext()){
//do stuff with input
}
else{
//handle stuff
}

Maths Game - returning points in methods

So my objective is to create a maths game where the user selects if he/she wants a maths question from a file or a random generate one consisting of the 4 maths elements in 3 difficulties.I have created a lot of methods... I have an idea where im going but now im stuck. I need to have it so it keeps a score of questions answered correctly. How do i return the points to the main method and have the game going until the user presses 3 on the gamePlay()method
public class MathsGameProject2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int score;
int points = 0;
int questionType;
System.out.print("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
questionType = keyboard.nextInt();
while (questionType != 3) {
if (questionType == 1) {
questionFromFile();
} else if (questionType == 2) {
randomQuestion();
} else {
System.out.println("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
}
}
}
public static questionFromFile() {
}
public static randomQuestion() {
Scanner keyboard = new Scanner(System.in);
int difficulty;
System.out.println("Please enter the difficulty you want to play." + "\n 1. Easy" + "\n 2. Medium" + "\n 3. Hard\n");
difficulty = keyboard.nextInt();
if (difficulty == 1) {
easy();
} else if (difficulty == 2) {
medium();
} else if (difficulty == 3) {
hard();
} else {
System.out.println("Please enter a number between 1-3\n");
}
}
public static easy() {
Scanner keyboard = new Scanner(System.in);
int mathElement;
System.out.print("What element of maths do you want?" + "\n1 Additon" + "\n2 Subtraction" + "\n3 Multiplication" + "\n4 Division\n");
mathElement = keyboard.nextInt();
if (mathElement == 1) {
easyAdd();
} else if (mathElement == 2) {
easySub();
} else if (mathElement == 3) {
easyMulti();
} else if (mathElement == 4) {
easyDiv();
} else {
System.out.println("Please enter a number between 1-4\n");
}
}
public static easyAdd() {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int num = rand.nextInt(10) + 1;
int num2 = rand.nextInt(10) + 1;
int correct = num + num2;
int answer;
System.out.print("What is the answer of " + num + " + " + num2 + " ?");
answer = keyboard.nextInt();
if (answer == correct) {
}
}
In order to keep track of how many questions the user answers successfully, you will need to:
For each question, return whether or not the user answered correctly
Have a counter which increments whenever a user answers a question correctly
Optionally, have a counter which increments whenever a question is answered wrong
For #1, you can use a boolean return value for specifying if the question was answered successfully.
return (answer == correct);
You will want to propagate that return value all the way up to the main() method.
static void main() {
....
boolean isCorrect = randomQuestion();
....
}
static boolean randomQuestion() {
....
return easy();
....
}
static boolean easy() {
....
return easyAdd();
....
}
static boolean easyAdd() {
...
return (answer == correct);
}
Then for #2 and #3, you can increment counter(s) defined in main based on the value returned by randomQuestion()
int numberCorrect = 0;
int numberWrong = 0;
....
boolean isCorrect = randomQuestion();
if (isCorrect) {
numberCorrect++;
} else {
numberIncorrect++;
}
Additionally (no pun intended), you can use a while loop to continuously receive user input until you get your exit code, which in this case is 3. One way to do this is to use a while(true) loop and break out when the user enters 3.
while (true) {
/* Get user input */
....
if (questionType == 3) {
break;
}
}
Finally, after your loop, you can simply print out the value of your numberCorrect and numberIncorrect counters.
Hope this helps.

How do you check to see if input is numerical, and if it's not, ask for one?

EDIT: None of the answers so far work. The closest I've gotten (Thank you, TNT) is using:
while (true) {
try {
value = s.nextDouble();
break;
} catch (java.util.InputMismatchException ex) {
System.out.println("That is not a number! Please enter a numerical value.");
}
}
but if the user inputs something like "foo", it puts me in an infinite loop saying "That is not a number! Please enter a numerical value."
My program here asks for an unit to choose from (fl.oz, gal, oz, lb, in, ft, or mi), asks how much of it they have, and asks for the unit they wish to convert to (mL, l, g, kg, mm, cm, m, or km).
My program works, refusing to convert from silly conversions such as gal to cm, telling you to re-input if they enter anything other than fl.oz, gal, etc.
The only thing I cannot figure out is if the user inputs something like "foo" when the program prompts the user for how much of the unit they have. My goal is to have the program say something like "That is not a number! Please enter a numerical value." If I run the program currently and enter anything but a numerical value, I get errors in the console. I'm pretty sure there is going to be loops involved, and I've looked up the API documentation for parse, but I'm still stuck.
Here is my program (it's long, sorry!):
import java.util.Scanner;
public class UnitConversions {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("What kind of unit do you have? Choose from: fl.oz, gal, oz, lb, in, ft, or mi. ");
String startingVariable = s.next();
while (!startingVariable.equals("fl.oz") && !startingVariable.equals("gal") && !startingVariable.equals("oz")
&& !startingVariable.equals("lb") && !startingVariable.equals("in") && !startingVariable.equals("ft") &&
!startingVariable.equals("mi")) {
System.out.println("That is not what I asked. Please choose from: fl.oz, gal, oz, lb, in, ft, or mi. ");
startingVariable = s.next();
}
System.out.println("How much of it do you have? ");
double value = s.nextDouble();
//here, I don't know what to put!
System.out.println("What would you like to convert to? Choose from: mL, l, g, kg, mm, cm, m, or km ");
String convertedVariable = s.next();
while (!convertedVariable.equals("mL") && !convertedVariable.equals("l") && !convertedVariable.equals("g")
&& !convertedVariable.equals("kg") && !convertedVariable.equals("mm") && !convertedVariable.equals("cm") &&
!convertedVariable.equals("m") && !convertedVariable.equals("km")) {
System.out.println("That is not what I asked. Please choose from: mL, l, g, kg, mm, cm, m, or km. ");
convertedVariable = s.next();
}
double result = 0;
if (startingVariable.equals("fl.oz")) {
if (convertedVariable.equals("mL")) {
result = (29.5735 * value);
} else if (convertedVariable.equals("l")) {
result = (0.0295735 * value);
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
if (result == 0) {
System.out.println("You cannot convert from " + startingVariable + " to " + convertedVariable + ".");
System.out.println("]:");
}
}
if (startingVariable.equals("gal")) {
if (convertedVariable.equals("mL")) {
result = (3785.41 * value);
} else if (convertedVariable.equals("l")) {
result = (3.78541 * value);
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
}
if (startingVariable.equals("oz")) {
if (convertedVariable.equals("mL")) {
result = (29.5735 * value);
} else if (convertedVariable.equals("l")) {
result = (0.0295735 * value);
} else if (convertedVariable.equals("g")) {
result = (28.3495 * value);
} else if (convertedVariable.equals("kg")) {
result = (0.0283495 * value);
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
}
if (startingVariable.equals("lb")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = (453.592 * value);
} else if (convertedVariable.equals("kg")) {
result = (0.453592 * value);
} else if (convertedVariable.equals("mm")) {
result = 0;
} else if (convertedVariable.equals("cm")) {
result = 0;
} else if (convertedVariable.equals("m")) {
result = 0;
} else if (convertedVariable.equals("km")) {
result = 0;
}
}
if (startingVariable.equals("in")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = (25.4 * value);
} else if (convertedVariable.equals("cm")) {
result = (2.54 * value);
} else if (convertedVariable.equals("m")) {
result = (0.0254 * value);
} else if (convertedVariable.equals("km")) {
result = (0.000025400 * value);
}
}
if (startingVariable.equals("ft")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = (304.8 * value);
} else if (convertedVariable.equals("cm")) {
result = (30.48 * value);
} else if (convertedVariable.equals("m")) {
result = (0.30481 * value);
} else if (convertedVariable.equals("km")) {
result = (0.0003048 * value);
}
}
if (startingVariable.equals("mi")) {
if (convertedVariable.equals("mL")) {
result = 0;
} else if (convertedVariable.equals("l")) {
result = 0;
} else if (convertedVariable.equals("g")) {
result = 0;
} else if (convertedVariable.equals("kg")) {
result = 0;
} else if (convertedVariable.equals("mm")) {
result = (1609344 * value);
} else if (convertedVariable.equals("cm")) {
result = (160934 * value);
} else if (convertedVariable.equals("m")) {
result = (1609.34 * value);
} else if (convertedVariable.equals("km")) {
result = (1.60934 * value);
}
}
if (result == 0) {
System.out.println("You cannot convert from " + startingVariable + " to " + convertedVariable + ". Sorry dude.");
System.out.println("]:");
} else {
System.out.println("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░");
System.out.printf(value + " " + startingVariable + " = %.3f " + convertedVariable + ".\n", result);
System.out.println("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░");
}
if (result > 10000) {
System.out.println("That's a lot of " + convertedVariable +"!");
}
}
}
You can use a while loop and try-catch for a situation like this. As long as something other than a double is entered, an InputMismatchException will be thrown, so the break statement will never be reached unless the user enters a number.
double value;
while (true) {
try {
value = s.nextDouble();
break;
} catch (java.util.InputMismatchException ex) {
System.out.println("That is not a number! Please enter a numerical value.");
s.nextLine();
}
}
s.nextLine();
The reason why it was in an infinite loop before was because the scanner continued attempting to parse the invalid input in the case that the user did not enter a number. The string kept causing an InputMismatchException to be thrown, which explains the infinite loop. Adding s.nextLine() consumes the invalid input and prevents this from happening. In the event that the user does enter a number, the s.nextLine() statement would consume the input so the user will be prompted to enter the next string.
I'm assuming the errors are along the lines of a conversion error? You need to catch the exception in a try block and you can then alert the user and get another input.
you need to catch the exception:
try
{
double value = s.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("This is not a number");
}
Use the try catch to handle this kind of situation.
when the user input non-numeric it will throw an exception then catch it then perform any thing you want from the catch block.
try{
System.out.println("How much of it do you have? ");
double value = s.nextDouble();
}catch(InputMismatchException ime){
System.out.println("This is not a number");
}
public class InputMismatchException extends NoSuchElementException
Thrown by a Scanner to indicate that the token retrieved does not
match the pattern for the expected type, or that the token is out of
range for the expected type.
"but if the user inputs something like "foo", it puts me in an infinite loop saying "That is not a number! Please enter a numerical value.""
It does not "put you in an infinite loop", it just keeps asking until you enter a number, like you asked in the original question. What would you like it to do instead?

The if(!found) statement is not working properly

the program will ask the user to enter the code of the item he wants to search for. if the item's code exists it will print it to the screen and all works fine until here. The problem is when the user enters code that not exists, the program won't work. it doesn't print "Item not found"
here is the code
public void searchItem(){
boolean invalidInput;
int q = -1;
do {
try {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = s.nextInt();
out: for (int i = 0; i<items.length; i++){
if(q == items[i].getCode()){
System.out.println(items[i].toString());
found = true;
System.exit(2);
}
counter++;
}
if(!found)
System.out.print("Item not found");
} catch (InputMismatchException e) {
System.out.println("Please enter a valid code [Numbers Only]");
s.next();
invalidInput = true; // This is what will get the program to loop back
}
} while (invalidInput);
}
If i use this (condensed form) of your code it works, and prints "Item not found" as we would expect... So the problem is somewhere else I feel....
Please provide further information about what happens if you enter a missing (but valid) item number!
public static void main(String[] args) {
boolean invalidInput;
int q = -1;
int[] items = { 1, 2, 3, 4 };
do {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = 5;
for (int i = 0; i < items.length; i++) {
if (q == items[i]) {
System.out.println(items[i]);
found = true;
System.exit(2);
}
}
if (!found)
System.out.print("Item not found");
} while (invalidInput);
}

Categories