Having trouble with calculations... what's wrong? - java

Having trouble calculating this out. The rest of the coding is fine but this one class. The error focuses on one line.
retail_price = double.parseDouble(input1) * (double.parseDouble(input2) / 100);
The errors tell me that "class expected" "; expected" and "not a statement". Where am I going wrong because this seems correct to me?
private class CalcButtonListener implements ActionListener
{
// The actionPerformed method executes when the user clicks the calculate button
public void actionPerformed(ActionEvent e)
{
double retail_price;
String input1;
String input2;
//Get the number from the users input in priceFeild1
input1 = priceField1.getText();
//Get the number from the users input in priceFeild2
input2 = priceField2.getText();
// Calculate out the operation below to find the retail_price
retail_price = double.parseDouble(input1) * (double.parseDouble(input2) / 100);
JOptionPane.showMessageDialog(null, "The retail price of the item is: $" + retail_price );
}

The name of the class containing parseDouble is Double, not double. They are not synonyms. double is the name of the primitive type, and primitives do not have methods.
So you need:
retail_price = Double.parseDouble(input1) * (Double.parseDouble(input2) / 100);
However, you should also strongly consider using BigDecimal instead of Double anyway, as that's a better match for currency values.
Additionally, I'd recommend:
Following Java naming conventions, using camelCase instead of underscore separators
Giving your variables more meaningful names - what are input1 and input2 meant to represent? A price and a discount, perhaps?
Declaring variables only where you need to, rather than at the start of the method
Considering what you want to happen if the value entered by the user isn't a valid number
Considering whether you care about internationalization (e.g. a user entering "10,50" instead of "10.50". If so, look at NumberFormat and DecimalFormat

Try:
Double.parseDouble(input1)

parsing of double retail_price = Double.parseDouble(input1) * (Double.parseDouble(input2) / 100);

Related

Data type recognition

I want to create a Java program where
a user will input something and the output will show what type of data the input is..?
For example:
Input: 25
Output: integer
Input: ABC
Output: string
Input: 12.7
Output: float/double.
Please help as I am clueless on how to work this out
This should work for your purpose:
import java.util.Scanner;
public class DataType
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
if(in.hasNextByte(2))
System.out.println("Byte");
else if(in.hasNextInt())
System.out.println("Integer");
else if(in.hasNextFloat())
System.out.println("Float");
else if(in.hasNextBoolean())
System.out.println("Boolean");
else if(in.hasNext())
System.out.println("String");
}
}
Note that the order of if...else statements is very important here because of the following set relations with respect to patterns:
All byte patterns can be integers
All integer patterns can be floats
All float patterns can be Strings
All booleans can be Strings
There are quite a lot of hasNext..() methods in the Scanner class, such as BigInteger, short, and so on. You may refer the Scanner class documentation for further details.
A simple approach could go like this; starting with some input string X.
If X can be parsed as Integer --> it is an int/Integer
Then you try Long
Then Float
Then Double
If nothing worked, you probably have a string there
( with "parsing" I mean using methods such as Integer.parseInt() ... you pass in X; and when that method doesn't throw an exception on you, you know that X is an Integer/int )
But: such a detection very much depends on your definition of valid inputs; and potential mappings. As there zillions of ways of interpreting a string. It might not be a number; but given a correct format string ... it could be timestamp.
So the very first step: clarify your requirements! Understand the potential input formats you have to support; then think about their "mapping"; and a potential check to identify that type.
You can get a string and try to parse it as other types:
Scanner s = new Scanner(System.in);//allows user input
input = s.nextLine();//reads user input
try{//java will try to execute the code but will go to the catch block if there's an exception.
int inputInt = Integer.parseInt(input);//try to convert input to int
catch(Exception e){
e.printStackTrace();//this tell you exactly what went wrong. If you get here, then the input isn't an integer.
}
//same with double

Regular Expressions for Floats

I am trying to get the regular expression for floats to work. I keep getting an error
Cannot invoke matches(String) on the primitive type float.
Any help? I'm kinda lost.
System.out.print("Enter $ amount of loan:");
payment = scanner.nextFloat();
while (!Regulations.paymentmatch(payment)) {
System.out.println("Information Not Correctly Entered");
System.out.printf("Please try again: ");
payment = scanner.nextFloat();
}
public static boolean paymentmatch(float a) {
return a.matches("\\d+.?\\d{2}");
}
If you want to allow the user to type a non-float value and then read it and tell them it's not a valid float value, you can't use nextFloat to read it, because...if it's not a valid float value, it won't work.
Either use hasNextFloat, which will tell you whether the scanner can read a float (but won't let you tell the user they typed something that wasn't a float), or use nextLine to read whatever they typed (as a String) and then validate that (via matches).

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

Trying to carry out calculations

I'm a beginner programmer (like only one day old) and I'm trying to come up with code that will be able to convert Celsius to degrees using the formula f-32 then display the result. I'm having some trouble since instead of showing the result this is what comes up. Kindly assist.
import java.util.Scanner;
public class Assignments (
public static void main(String args[]) {
Integer Celsius, Faren;
Scanner Celsius = new Scanner(System.in);
System.out.prinln(" Enter value in Celsius: ");
int name = Celsius.nextint();
Faren = Celsius + 32;
}
}
Here's my result after running:
Your code uses variable Celsius as two different types. It cannot be Scanner and Integer at once.
Try something like this:
Scanner scanCelsius = new Scanner(System.in);
System.out.prinln(" Enter value in Celsius: ");
int c = scanCelsius.nextint();
int f = c + 32;
By the way, the convertion to Fahrenheit is wrong. The correct formula is:
Fahrenheit = Celsius * 1.8 + 32
Thus you have to use float:
float f = (float)c * 1.8 + 32;
You have two main problems that I can see. Firstly, as #Manu mentioned in the comments, you are trying to use the variable name Celcius twice. This is not allowed, each variable should have a unique name. Try renaming the Scanner to celciusScanner or something like that.
Secondly, you have a print statement (X celcius are Y farenheit) which is not formatted correctly. You need a plus between the variable Faren and the following string. However I don't see this line in your code, I guess you must have removed this.
A couple of general comments too. Your variable names should always begin with a lower case letter. Names beginning with an upper case letter are generally reserved for classes. Sticking to conventions like this makes it much easier to read your code. I would also look into the difference between int and Integer. It looks like you have two variables defined as Integer, but it seems that int will do the job.
Overall though, not a bad attempt and these issues are very common with beginners.

Changing an object's value according to user Input

I am trying to figure a way in how to change an object's value. I've made a class in which it contains set and get for the object and 3 sorts of values being PRICE, QUANTITY and NAME.
The price and name are already set in the test class
System.out.println("How many would you like?");
String quantity = s1.nextLine();
quantity = food1.setQuantity();
quantity = food1.setQuantity(); is wrong. How do I change it according to how much quantity the user wants?
You may try with:
quantity = food1.setQuantity(Integer.parseInt(quantity));
instead of:
quantity = food1.setQuantity();
I don't mean to sound harsh, but programming isn't magic. Look at what you're doing:
String quantity = s1.nextLine();
quantity = food1.setQuantity();
You're overwriting the string with what one would hope to be a void set method. Instead, the method should be a void set method, which accepts an integer, so you would do the following (assuming proper function implementation):
String quantity = s1.nextLine();
food1.setQuantity(Integer.parseInt(quantity));
Not sure if you learned Exception handling yet, but you should wrap this in a try/catch if you have. If not, you can use regular expressions to see if it's an integer, if that is necessary. Odds are this is a class assignment, and you're probably assuming that the input is valid or using exception handling. Good luck.
Assuming, that the quantity is supposed to be an integer, you could write this:
String quanity = s1. nextLine();
//check that quanitity is a valid number before trying to parse it as a number
if(quantity.matches("\\d+"))
{
food1.setQuantity(Integer.parseInt(quantity));
}else
{
System.out.println("The quantity you entered is not a valid number.");
}

Categories