Trying to carry out calculations - java

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.

Related

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ':'

I was trying to run my code with a scanner and suddenly it errors when it goes to the 2nd question.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner stats = new Scanner(System.in);
double base,current;
float bonus;
int level;
System.out.print("Enter the base attack speed: ");
base = stats.nextDouble();
System.out.printf("Enter the bonus attack speed %: " + "%.2f");
bonus = stats.nextFloat();
System.out.println("Enter the level: ");
level = stats.nextInt();
current = (base*1+bonus*level-1) /100;
System.out.print("The character's current speed is: " + current);
}
}
% is what printf (and String.format) use for identifying a placeholder which will be filled in by a parameter provided as second argument.
You therefore have 2 bugs in this code:
The % in attack speed %: is being identified by printf as a placeholder, but you want to print an actual percent symbol. To print that, write 2 percent symbols, which is 'printf-ese' for a single percent symbol: "Enter the bonus attack speed%%: ".
You then add "%.2f" to it which is bizarre, what do you think that does? As written, if you fix the bug as per #1, you immediately get another exception because this requires an argument. The idea is that you can do something like: System.out.printf("The speed of the vehicle in km/h is: %.2f", someValue);. If someValue is, say, 39.8993, that will print the string "The speed of the vehicle in km/h is: 39.90", because you asked for: Print a value as floating point value with max 2 fractional digits. You don't have any input to print there - you're still asking the user, and you can't use this kind of thing to 'format' what the user is supposed to put in. That comes later. So presumably you want to just get rid of that entire "%.2f" thing there.

Trying to make a weight converter that converts a weight in kg to stones, pounds and ounces- Java

I would like to create my own Converter class which will take an input weight from terminal and convert it to stones, pounds and ounces. I wondered how I would go about this?
I will create a method within this class called converter, and I wondered whether all my calculations should be within this method or whether I need more methods? I am anxious I haven't gotten the right idea of implementing my own methods yet.
also, would I put the input weight (using EasyIn library)as a parameter for this method?
Any examples would be much appreciated!
Many thanks!
are you trying the console in eclipse or other IDE, than look at system.in
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
welcome to stack overflow. Luckily, all you need to do is write some basic methods that perform math.
public double convertStone();
{
// conversion code here
}
And you can repeat that for each value you need. For the conversion code, you only need to convert the actual math for, say, KG to LBS into code like so:
kgToLbs = kg * 2.21;
Hope this helps!
javaI worked on a project similar to this one. What I did was I posed a question within the terminal asking which conversion they would like to do, which would then prompt some "if" statements that run the selected conversion. This may not be exactly what you're looking for, but it's useful if you're unsure about inputting your own methods.
String selection;
double weight, stones;
Scanner sc = new Scanner(System.in);
//Print statements asking the user what conversion they would like to do
selection = sc.nextLine();
if(selection.equalsIgnoreCase("stones"))
{
//conversion
}
//etc

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!

New to Java -> Method Issues

Pretty sure that I'm missing something fairly obvious here, but I've only been at it a few days. Any help would be much appreciated. I managed to get my class with methods I would like to use to compile, by my main method I was planning link all my results to is getting an error. It says my actual arguments and formal are different. I assume I didn't connect them to the other class or something, but I'm kind of lost. Thanks again!
public class SphereAndCone {
public static void main(String[] args) {
Calc calc1 = new Calc();
Scanner input = new Scanner(System.in);
System.out.print("What is the radius?");
// set sphere/cone radius
double r = input.nextDouble();
System.out.print("What is the height?");
// set sphere/cone height
double h = input.nextDouble();
// print results while calling on methods
System.out.printf("Sphere Volume: %3f16" + calc1.sphereVolume());
System.out.println();
System.out.printf("Sphere Surface: %3f16" + calc1.sphereSurface());
System.out.println();
System.out.printf("Cone Volume: %3f16" + calc1.coneVolume());
System.out.println();
System.out.printf("Cone Surface: %3f16" + calc1.coneSurface());
System.out.println();
}
}
The System.out.printf() method has the following signature (String, Object...) (according to the JavaDoc).
Now lets go to your code:
System.out.printf("Sphere Volume: %3f16" + calc1.sphereVolume());
The + sign concatenates the two values. The result will be a String because the first argument is a String. So lets assume that calc1.sphereVolume() returns 1.0. The VM will convert the 1.0 float value to String and you will get the newly create "Sphere Volume: %3f161.00000000000000" String. When the JVM tries to execute the printf method it sees that there is a placeholder (the "%3f16") and it searched in the varagrs (the Objec... parameter). It sees that there is no varargs an throws an exception. So basically this is what happens :)
Hope this was helpful :)

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

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);

Categories