I am getting this message:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at fdc.programming.VendingMachine.InsertMoney(VendingMachine.java:70)
at fdc.programming.VendingMachineDriver.main(VendingMachineDriver.java:30)
Java Result: 1
I had been trying to work out, how to do a validate loop so that only positive integers can be accepted and I gave up for now, but I did not change anything and put everything back as it was before messing around. Now when I try to enter a number it gives the above error but there are no errors in Netbeans that I can use to figure out what is wrong! Please be aware that I have only done one basic module in Java for college ;)
My code is:
public class VendingMachine
{
String sinsertMoney, sinsertMoney2; // Money inserted value for parsing into int
String productName; // Name of product
int insertMoney, insertMoney2; // Money inserted by customer (int = pence)
int price; // Price of products on sale
int changeLeft; // Change left from inserted money after selection
int again; // variable for deciding program repeat
DecimalFormat pence = new DecimalFormat("#p"); // Format display output for pence
public void InsertMoney() {
String soption; // Variable for machine operation
productName = " Nothing";
insertMoney = 0; // Default inserted money initialised to zero
insertMoney2 = 0; // Default additional inserted money initialised to zero
price = 0; // Initialising money variables
// Vending machine welcome dialog
soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");
if ("q".equals(soption)) { // If user chooses q: quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
}
if ("i".equals(soption)) { // if user chooses i: insert money
JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney); // Parsing for calculations
}
if ("s".equals(soption)) { // if user chooses s: select item
}
}
I can't see where you've declared sinsertMoney but it looks like you've forgotten to assign the result of your call to JOptionPane.showInputDialog to something, hence why that value is still null when you try to parse it.
Try this:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney);
You need to get the entered value in sinsertMoney like:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n=============================");
And also implement null check on the sinsertMoney for cancel operation and empty strings.
Related
I have searched to see if there was a question like this already but I did not find one. So for this school project, I am supposed to make a program with arrays to look up and print the names and prices for coffee orders. I have most of the program done but I only get one dialog box to pop up and if I add an XXX it quits the system completely without giving an output.
I know if I add some more addIn = JOptionPane.showInputDialog("Enter coffee add-in or XXX to quit: "); it would give me another pop-up window but I am still having trouble with it has I want it to give me one line at a time like if I say "Cream" it says "Cream price is $0.89" and if I enter "Vanilla" it says "Sorry we do not carry that" and when I enter "XXX" it would just says "Order total is $2.89".
import javax.swing.*;
public class JumpinJive
{
public static void main(String args[]) throws Exception
{
// Declare variables.
String addIn; // Add-in ordered by customer.
final int NUM_ITEMS = 5; // Named constant
// Initialized array of add-ins.
String addIns[] = {"Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey"};
// Initialized array of add-in prices.
double addInPrices[] = {.89, .25, .59, 1.50, 1.75};
boolean foundIt = false;
int x; // Loop control variable.
double orderTotal = 2.00; // All orders start with a 2.00 charge
// Get user input.
addIn = JOptionPane.showInputDialog("Enter coffee add-in or XXX to quit: ");
// Write the rest of the program here.
for(int it=0; it < NUM_ITEMS; it++){
if(addIns[it].equals(addIn)){
//Output the product name and the price
System.out.println("Name of the product :" + addIns[it] + "\nPrice of the product:" + addInPrices[it]);
//Output the total for the price of the product
System.out.println("Total Price of the product :"+ (orderTotal + addInPrices[it]));
//If foundIt is true
foundIt = true;
break;
}
}
//See if it is found
if(foundIt)
{
//Prints a Error Message
System.out.println("Sorry, but we do not carry that product.");
}
} // End of main() method.
} // End of JumpinJive class.
Am I missing something or am I misinterpreting possibly what the assignment is going for? Thank you in advance!!
but I only get one dialog box to pop up and if I add an XXX it quits the system completely without giving an output
You need some kind of loop, maybe something like...
do {
// Get user input.
addIn = JOptionPane.showInputDialog("Enter coffee add-in or XXX to quit: ");
if (!addIn.equals("XXX")) {
// Write the rest of the program here.
}
} while (!addIn.equals("XXX"));
I'd recommend having a look at Control Flow Statements and have a look a the The while and do-whole statements for more details
Also, you're not keeping a running total of the order...
So, instead of...
System.out.println("Name of the product :" + addIns[it] + "\nPrice of the product:"
+ addInPrices[it]);
//Output the total for the price of the product
System.out.println("Total Price of the product :" + (orderTotal + addInPrices[it]));
Maybe something like...
String item = addIns[it];
double price = addInPrices[it];
orderTotal += price;
JOptionPane.showMessageDialog(null, item + " is $" + price + " - Order total: $" + orderTotal);
will keep track of the current order total
And this...
if (foundIt) {
//Prints a Error Message
System.out.println("Sorry, but we do not carry that product.");
}
Is going to display an error message when the item is found (i.e. if (true) {...}, you want to negate the question, maybe something like...
if (!foundIt) {
JOptionPane.showMessageDialog(null, "Sorry, but we do not carry that product.");
}
I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have 1 issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total. The code works, but for some reason when I test it I have to enter "add" twice before it runs; is there anyway I can fix this?(I left out a bunch of code in the middle as I feel it wasn't important to this question.)
//local constants
final int QUIT = -1;
final String ADD = "add";
final String SUBTRACT = "subtract";
//local variables
int soldItems;
String addition;
String subtraction;
String nameFirst;
String nameLast;
//while the input is not QUIT
while(soldItems != QUIT)
{
//Clear screen then prompt the user to add or subtract
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.print(Util.setLeft(35, "Add or Subtract: "));
addition = Keyboard.readString();
subtraction = Keyboard.readString();
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//if the user enters add the program will add to the employee total
if(addition.equals(ADD))
{
info.addition(soldItems);
}
//else the program will subtract from the employee total
else
{
info.subtraction(soldItems);
}
//Displays the employee information and prompts the user for the next sales figure
System.out.println(info.toString());
System.out.println();
System.out.print(Util.setLeft(40, "Input the next Sales Figure: "));
soldItems = Keyboard.readInt();
}//end while
//clear screen
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//End of program message and Final employee information
System.out.print(Util.setLeft(45, "Final Employee Information"));
System.out.println(info.toString());
addition = Keyboard.readString();
subtraction = Keyboard.readString();
You dont need to use two of them, just use input = Keyboard.readString(); and then check the input and process it accordingly.
I'm trying to write a program that needs to stop when the target of £500 has been met. I have to use a DO WHILE loop to do this.
It needs to record how many donations it receives before it reaches £500, also it needs to record the name of the person with the highest donation given and what the largest donation was.
I cannot get the program to update the name of the person with the highest donation. The code I have so far is below. Please tell me where I am going wrong.
I have a red line coming up under 'namemax' when I try to call it at the end outside of the loop, saying 'not initialized'
enter codeimport java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 11/02/2015
* Time: 15:45
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class DoWhile
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
final double TOTAL=500;
String name,namemax;
double donation, donationTotal=0,currentMax=0;
int howManyDonation=0;
do
{
System.out.println("Please enter your name below");
name = keyboard.next();
System.out.println("");
System.out.println("Please enter the amount you would like to donate below");
donation = keyboard.nextDouble();
howManyDonation++;
donationTotal = donationTotal+donation;
if(donation>currentMax)
{
currentMax=donation;
namemax=name;
}//if
}//doWhile
while(donationTotal!=TOTAL);
System.out.println("The total number of donations is " + howManyDonation);
System.out.println("The largest donation was " + currentMax);
System.out.println("The name of the person with the largest donation is " + namemax);
}//main
}//class
here
Just change this line
String name,namemax;
into this:
String name,namemax = null;
Furthermore, change this
while(donationTotal != TOTAL);
into this:
while(donationTotal < TOTAL);
You have a pretty simple problem here. You are updating namemax inside of an if loop only. That means that as far as the code is concerned, there is a possible situation in which it could never be assigned. In practice, because of what you are doing, that can't actually happen but the compiler doesn't understand that.
To fix it,
change
string name,namemax;
to
string name;
string namemax = "";
That should take care of it.
it gives at least one sutuation where namemax not will be set. So you have to initialize the string.
Simply change
String name,namemax ;
To
String name,namemax = null;
or
String name,namemax = "";
The compiler can't guarantee that you'll actually set the namemax before you exit the loop. You should initialize namemax to the empty string to fix this problem.
So everything is working fine for this calculator besides for the askCalcChoice1. Since askCalcChoice1 is a string, I am calling it wrong (obviously). The error says it cannot convert string to int, as well as convert int to boolean. However, when i make the inputOperation as a string, it breaks the other 2 calls below askCalcChoice1. (it breaks displayRedults and askTwoValues because those are not strings). I do not know how to format askCalcChoice in order to call for this method that is written in another class wihtout breaking anything. askCalcChoice is written as a string which i pasted below the oopCalculator code. Is there any way and can someone please show me how to write that portion of that code in oopCalculator?
int inputOperation; // user to choose the function
askCalcChoice1 myAskCalcChoice1 = new askCalcChoice1();
//menu becomes a complete string below
String menu = "Welcome to Hilda Wu's Calculator\t\t"
+ "\n1. Addition\n"
+ "2. Subtraction\n"
+ "3. Multiplication\n"
+ "4. Division\n"
+ "5. Exit\n\n";
calculatorCommands.pickNewSymbol(menu); //complete menu will be picked up as a string and display
calculatorCommands.putDownSymbol();
while (inputOperation = myAskCalcChoice1.calcChoice()) { //this will call for myAskCalcChoice1 class
calculatorCommands.pickNewSymbol("\n"); //pick up the class
calculatorCommands.putDownSymbol(); //display the class
askTwoValues myAskTwoValues = new askTwoValues();
float[] myFloats = myAskTwoValues.inputFloats(inputOperation);
displayResults myDisplayResults = new displayResults();
float result = myDisplayResults.showResults(inputOperation, myFloats);
String strFormat = "The answer is: " + result + "\n\n"; //print out The answer is as a string
calculatorCommands.pickNewSymbol(strFormat); //pick up string from above
calculatorCommands.putDownSymbol(); //display string
calculatorCommands.pickNewSymbol(menu); // pick up menu from the beginning of code, loop to calculator menu
calculatorCommands.putDownSymbol(); //display menu as loop
}
calculatorCommands.pickNewSymbol("\nThank you for using Hilda Wu's Calculator\n"); //when user choose to exit calculator
calculatorCommands.putDownSymbol();
}
String calcChoice() {
String input;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for Subtraction, M for Multiplication, or D for Division, or X for Exit: ");
try {
input = readInput.nextLine(); //user will enter a response
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D") || input.equals("X")) {
System.out.println("Thank you");
break; //user entered a character of A, S, M, or D
} else if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5) {
System.out.println("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have entered an invalid choice, please try again.");
}
continue;
}
catch (final NumberFormatException e) {
System.out.println("You have entered an invalid choice. Try again.");
continue; // loop will continue until correct answer is found
}
} while (true);
return input;
}
}
To start with, you are calling showResults with two arguments:
int choice
and
float [] f
Choice is never used.
You use input variable instead in your switch but on default you return the error showing choice.
Better pass choice as an argument in the function and be sure it is char and not other type.
Also this is not the form of a good stated question. I will not rate it down but please remake it so the whole code is correctly shown. I can not make sense of it easily. I might misunderstood it already. Please do not add comments between, be sure you have correct indentation and you got all the code in.
If you need to comment do it afterwards. It's not very complicated, just show us the code and ask what is wrong later ;)
If choice was meant to pass in the switch... then do it, but not as int but as char.
I am new to the forums so first of all I'd like to say "Hi"! I'm new to Java programming and am trying to make a simple payroll calculating program with three while loops.
The first while loop keeps the program going until the user enters the sentinel "stop". The second and third loops are error traps that ensure the user enters a positive number before continuing.
For some reason, the while loops are not working and I have tried every variation I can think of. The program runs just fine, it just ignores the while loops. If someone could provide some suggestions as to what I'm doing wrong, I'd really appreciate it.
I'm using NetBeans 8.0 IDE if that helps.
Here is my code:
Import java.util.*;
Import java.text.*;
public class PayrollProgramVersion2
{
//begin main program
public static void main(String[] args)
{
//declare new scanner
Scanner sc = new Scanner (System.in); // declare new scanner object
DecimalFormat Dollars = new DecimalFormat ("$0.00"); //format for dollars
String Employee; //employee's name
Double Hours, //hours worked
Rate, //pay rate
Pay; // Hours * Rate
Boolean Continue = true; // sentinel for program loop
//welcome user, prompt for employee name, and assign input to Employee
System.out.println ("Welcome to the payroll program!");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
// while loop continues program until user enters "stop"
while (Continue == true)
{
if (Employee.equalsIgnoreCase("stop"))
{
Continue = false;
} // end if
else
{
//prompt for hours worked and assign to Hours
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
Hours = sc.nextDouble();
}
//prompt for pay rate and assign to Rate
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
//this block is an error trap to ensure input is positive before continuing
while (Rate < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println( "How much does " +Employee+ " make per hour?");
Rate = sc.nextDouble();
}
Pay = Hours * Rate; // calculate payrate
//display results
System.out.println(Employee+ "'s paycheck is " +(Dollars.format(Pay))+ ".");
System.out.println ("What is the employee's name? (Enter stop to quit.)");
Employee = sc.nextLine();
} //end else
} //end while
System.out.println ("Thank you for using the payroll program. Goodbye!");
} // end main
} // end program
From what I can see you should make your while (hours<0) to while (hours<0 || hours == null).
This is because... As far as I can see you initialise hours. But no value is input into it. So it remains as null. You could also try changing the while to an if.
Hope this helps. It may be that it does default to 0 but it may be worth for testin purposes to have a console output.
System.out.println(hours);
Befor the while loop to see what your program is reading hours as.
Hope this helps.
The error is that nextDouble does not eat the newline. It skips newlines at the beginning, so in effect only the last nextDouble is concerned.
Best to make a utility function:
Instead of
Hours = sc.nextDouble();
call your own function:
Hours = nextDouble(sc);
private static double nextDouble(Scanner sc) {
double value = -1.0;
if (sc.hasNextDouble()) {
value = sc.nextDouble();
}
sc.nextLine();
return value;
}
Use a small initial letter for field and method names.
Use double/boolean/int instead of the Double/Boolean/Integer as the latter are Object wrappers (classes); the first primitive types.
Call sc.close(); (for good order).
Aside from what has been said above:
sc.nextDouble consumes and returns the next input from the current line. It does not forward the line.
sc.nextLine consumes and returns the input from the current line and forwards to the next line
At the end of your while loop you call Employee = sc.nextLine(); If you follow your logic and only input allowed values, this will always return an empty string as it consumes the current line where your most previously removed double was stored(now empty string "")
When you do something like:
Hours = sc.nextDouble();
you trust the user to enter a double value, and in case the user entered illegal value, a String for example, this line will throw an exception.
You can solve it like this:
while (Hours < 0)
{
System.out.println( "Error - input must be a positive number");
System.out.println ("How many hours did " +Employee+ " work?");
String hours = sc.nextLine();
try {
Hours = Double.valueOf(hours);
}
catch (NumberFormatException e) {
// keep looping until we get a legal value
Hours = -1.0;
}
}