Question:
JAVA -- WHAT's Wrong with my code?
?
2009-05-27 18:45:11 UTC
import java.util.Scanner;
public class if_test
{
public static void main (String Args[])
{
double new_value=0.0;
double orig_value;
String new_unit;
String orig_unit;

Scanner scan = new Scanner (System.in);

System.out.print ("Original Unit:");
orig_unit=scan.nextLine ();

System.out.print ("New Unit:");
new_unit=scan.nextLine ();

System.out.print ("Original Value:");
orig_value=scan.nextDouble ();

if (orig_unit=="AUD")
{ if (new_unit=="AUD")
new_value=orig_value;
if (new_unit=="HKD")
new_value=(orig_value*0.837676/0.161422);
if (new_unit=="USD")
new_value=(orig_value*0.837676/1.252920);
}
if (orig_unit=="CAD")
{ if (new_unit=="CAD")
new_value=(orig_value);
if (new_unit=="HKD")
new_value=(orig_value*(1.0/0.161422));
if (new_unit=="AUD")
new_value=(orig_value*(1.0/0.837676));
if (new_unit=="USD")
new_value=(orig_value*(1.0/1.252920));
}
System.out.println ("New Value is: " + new_value);
}
}

Your suppose to enter one of the following units: AUD, HKD, CAD, and USD. Then you ae supose to enter the unit you want to convert to and it makes the conversions.....
Five answers:
what?
2009-05-27 19:01:38 UTC
You're using arithmetic operators on strings.



orig_unit=="AUD"



should be



orig_unit.equals("AUD");



Also, your class name is unconventional.
owsley's kid
2009-05-27 18:56:52 UTC
In the AUD original unit if, you don't have a conversion for CAD.

There is no code for original units of HKD or USD.
HandyManOrNot
2009-05-27 19:08:51 UTC
Class names must begin with uppercase and should not contain underscores.



Comparison operator for String is String.equals(String), not ==.



You should use else if instead of a series of if statements. If only one condition can be true, it should be:

if(a) {

//do something

}

else if(b) {

//do something

}

else if(c)



- you get the idea.



Always use brackets {} to surround your code blocks. You have ambiguous grouping in your if statements, you are actually nesting each if inside the previous one. Make explicit statements separate from each other as in my example above, don't make it difficult to read.
legion_2k
2009-05-27 18:58:14 UTC
Not a java guy but from what I understand java is case sensitive and java key words are always in lower case. Your string deceleration is "String" and not "string". Otherwise it would help if you told tell us what happens when you try to test it.
The Phlebob
2009-05-27 18:53:02 UTC
Without knowing what's going wrong for you (could be anything from a compile error to bad output to a fatal error), it's going to be hard to help you. More information, please?



Sorry.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...