JOptionPane.showInputDialog is only showing up once - java

import java.util.Scanner;
import javax.swing.JOptionPane;
public class moneyRate {
public static void main(String[] args) {
//Get Inputs
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog("How many old pounds? ");
double oldPounds = input.nextDouble();
JOptionPane.showInputDialog("How many old shillings? ");
double oldShillings = input.nextDouble();
JOptionPane.showInputDialog("How many old pennies? ");
double oldPennies = input.nextDouble();
input.close();
//New Pounds calc
double newPounds = ((oldPounds*160.80) + (oldShillings*8.04) + (oldPennies*0.67));
System.out.print("Your old pounds shillings and pennies are equal to £4"
+ "" + newPounds + ".");
}
}
In a programming class we were asked to make a program that would tell the user how much their old pounds shillings and pennies are worth in today's pounds. I had this fully working using the console as input and output for the program, but now when I try to do it using JOptionPane, to present the user with small pop-up boxes it won't work. When I run the task only the first pop-up shows and the program just ends without any form of error message. I'm assuming this is a simple mistake with syntax but I can't spot it.
If anyone spots the mistake, please help me out, thanks :)

The way you are using JOptionPane and Scanner cause the issue.
JOptionPane.showInputDialog("How many old pounds? "); // display this
double oldPounds = input.nextDouble(); // then it wait for scanner input
Now your program will hold there for expecting input from console. You need to change your code as follows
double oldPounds = Double.parseDouble(JOptionPane.showInputDialog("How many old pounds? "));
double oldShillings = Double.parseDouble(JOptionPane.showInputDialog("How many old shillings? "));
double oldPennies = Double.parseDouble(JOptionPane.showInputDialog("How many old pennies? "));
double newPounds = ((oldPounds*160.80) + (oldShillings*8.04) + (oldPennies*0.67));
System.out.print("Your old pounds shillings and pennies are equal to £4"
+ "" + newPounds + ".");

What are you doing there? After you show the Dialog you read from the command line. You should take the value from the inputDialog.

Ruchira answer is complete.. just notice that
JOptionPane.showInputDialog()
returns a string.
That's why you need the Double.parseDouble conversion he put in the code.

Related

How to save input from if statement and output it in another block in java [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 5 years ago.
Im just a beginner and anything would be helpful. So basically this program asks a question and depending on input, affects the price of tshirts. Also it asks how many tshirts wanted to be purchased also affecting the price. It keeps on running until "exit" is typed.
The problem I have is that I want the output to have the total sales and other info that was accumulated from the if/else if statements before. But when I compile it says local variable may not have been initialized. Any help would be much appreciated
import java.util.Scanner;
class ScannerTest{
public static void main (String args[]){
int b, c;
String endProgram = "exit";
String userInput;
java.util.Scanner input = new java.util.Scanner(System.in);
do{
System.out.println("\n Welcome to the SAC t-shirt sales software");
System.out.println("\n Does the student have an activity fee? Yes/No/Exit");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase("yes")){
System.out.println("How many Tshirts do you want to buy?");
b = input.nextInt();
input.nextLine();
System.out.println("Cost:" + b*5 + " dollars");
}
else if(userInput.equalsIgnoreCase("no")){
System.out.println ("How many Tshirts do you want to buy?");
c = input.nextInt();
input.nextLine();
System.out.println("Cost:" + c*6 + " dollars");
}
}while (!userInput.equalsIgnoreCase(endProgram));
System.out.println ("Activity Card Sales:" + b + "Non-activity Card Sales:" + c + "Total Money Collected" + ((b*5)+(c*6)));
input.close();
}
}
just set in the begging b and c to 0 and you will have no problems.

How to stop scanner from accepting input

I'm working on very simple code which asks you to enter how much money you have and and which products you wish to buy (on one line). The program is then supposed to tell you whether you have enough money to buy the products or not. Also, it should print the product with the lowest price.
Example:
Enter amount of money you have: 100
Enter products you want to buy and the value for each: Apple 10 and Orange 20
Output of the code:
you have enough money
the lowest price is (Apple 10)
I have 2 problems with this code
First, when I try to stop the scanner from taking inputs I'm supposed to enter "stop" as an input. However, in my case the action is only performed only if I enter "stop" 2 times. I don't know why.
I need to determine the minimum product value and print it. I have tried a lot of different things, but none of them worked for me.
This is my code so far:
Scanner input = new Scanner (System.in);
String productName="";
double totalPrice=0;
double productValue = 0;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (!(productName.equals("stop")) ){
if(input.hasNext()){ productName = input.next();}
if (input.hasNextDouble()){ productValue = input.nextDouble();}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
Your code is reading two items before checking to see if the user wants to stop and that is why you're having to provide two inputs. To determine the minimum value just keep track of the lowest value you've seen so far along with the name associated with that value.
Scanner input = new Scanner (System.in);
String productName="", minProductName = null;
double totalPrice=0;
double productValue = 0, minValue = -1;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (true){
productName = input.next();
if("stop".equals(productName))
break;
productValue = input.nextDouble();
if(minValue < 0 || minValue > productValue){
minValue = productValue;
minProductName = productName;
}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
System.out.println("Minimum product value: "+minProductName + " " +minValue);
input.close();
Input/Output:
How much money do you have?
100
please insert the items in the invoice (the name of product and its price): insert "stop" as the name of the product to finish your input
apple 10
orange 5
banana 50
stop
you have enough money
Minimum product value: orange 5.0
Considerations/Notes:
You may notice that this condition has been flipped:
if("stop".equals(productName))
This is intentional because if you have a null productName somehow then your code will throw a null pointer if you use productName.equals(...) but if you use a constant like "stop" there is no way this can be null so it will never throw a NullPointerException.
You never validate your input - what if the user enters something that is less than zero for the value? Is that valid? If not then what should happen?
Instead of parsing the user input the way you are now, try parsing the entire line at once and then splitting up the input string using String.split()
Also consider what the your first call to Scanner.nextDouble() is really doing. It will read the next double input by the user but will not read to the next line (won't read past the newline character)

Why is nextDouble() from the Scanner method sending me "Exception"

I'm suppose to enter 2 numbers, one int that is the amount to withdraw and one double which is the balance (with a space between them). Since every withdraw charges a fee of 0.5, balance must be a double. And thats what must be printed.
I get error at nextDouble, why? I have just 1 month coding, I thought this was going to be a piece of cake, I think BASIC syntax ruined me 30 years ago :(
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//init variables
int amount;
double balance;
//insert amount and balance
Scanner input = new Scanner (System.in);
amount = input.nextInt();
balance = input.nextDouble();
//reduce amount+fee from balance
balance=balance-(amount + 0.50);
//print new balance
System.out.print(balance);
input.close();
}
}
It is dependant on Locale, try to use comma instead of a dot or vice versa.
Ex: 1,5 instead of 1.5
You can check, if there is some int or double to read.
And you have to use , or . depending on the country, you are.
If you need it country independent, read it as string and parse then (see below)
A solotion would be to read the line as a string and parse it then to int and double.
Checking if double is available:
input.hasNextDouble();
Read as String:
String line = input.nextLine();
String[] sl = line.split(" ");
amount = Integer.parseInt(sl[0]);
balance = Double.parseDouble(sl[1]); //solve the problem with . and ,
You also could check if there are enough inputs.

How to multiply a set number and a user input number in Java?

I want to make a calculator that greets the user by name then multiplies one number that the user enters and one number that I set. For instance, if the user enters the number 10, I want my code to take the 10 and multiply it by 6.
Here's what I have so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello" + userName + "how many steps do you take in a ten second interval?");
}
}
This part is working, but I can't figure out what to do next.
If you take a look at the Javadoc for Scanner, there is a nextInt() method, which will do the same thing as nextLine() but return an integer. You can set that to an integer variable.
To multiply two variables, it's as simple as
int z = x * y;
Then print out the result, or to simplify it, you could just print out the calculation without setting it equal to a variable
System.out.println("The awnser is: " + (scanner.nextInt() * 6));
Keep in mind, this are integers, you could also use doubles or floats, or even longs. See the scanner documentation for all the methods you can use to get input.
Use nextInt() (or nextDouble() or ...) method to read the number the user will input.
int userNumber = (userInputScanner.hasNext()) ? userInputScanner.nextInt() : 0;
System.out.println("6 * " + userNumber + " = " + (6 * userNumber));

Declaring a Double in Java

import java.util.Scanner;
class Calculator
{
public static void main(String args[]){
Scanner mortgage = new Scanner(System.in);
System.out.println(mortgage.nextLine());
double iRate;
double lAmount;
double answer;
System.out.println("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println(answer);
}
}
My question is I don't think I am declaring the double correctly and am getting an error. How do I declare the double correctly so the program runs without error
That code compiles fine although:
System.out.println(mortgage.nextLine());
seems a bit strange since you wait for a line then print it out. Not sure why you would want to do that.
The following code with that line removed and some cosmetic changes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner mortgage = new Scanner (System.in);
double iRate, lAmount, answer;
System.out.println ("Enter interest rate");
iRate = mortgage.nextDouble();
System.out.println ("Enter loan amount");
lAmount = mortgage.nextDouble();
answer = iRate + lAmount;
System.out.println ("Answer is " + answer);
}
}
outputs:
Enter interest rate
10
Enter loan amount
50000
Answer is 50010.0
You may also want to rethink the way in which you do interest rate calculations. Anyone who's ever done work for a bank would get a giggle out of that.
The general way to calculate the interest due on some capital for a given percentage rate would be something like:
answer = iRate / 100.0 * lAmount;
although I realise you may have intended to clean that up once you get past your immediate problem, so apologies for that friendly jab :-)
I'm having to guess since you didn't specify the error, but it's likely coming from your usage of mortgage.nextDouble();. nextDouble(); will read JUST the next double from the line you type in, meaning there will be a trailing newline character at the end, which will result in it behaving in ways you don't expect.
There's a few alternative ways to go about it, so I'll just show one here:
double iRate;
iRate = Double.parseDouble(mortgage.nextLine());
Mind you, this does as much sanity checking as your code (as in, none!). What this does is read in a line of input, and then have the Double class convert the resulting String into a Double, which is stored in the double iRate.
If you want your "Enter interest rate" line to appear first, remove System.out.println(mortgage.nextLine());; it's not doing anything. Your program is waiting for an input before it can proceed, which I think was your problem.
Don't use double's (or float's) for money or any other calculations, have a look at this article "don't use floats for money". basicly it IEEE 754 giving you all kind of rounding errors.

Categories