Jump to content

I am making a Java program in the Eclipse IDE to convert base 10 numbers to hexadecimal and back. Right now it is not working. Here is my code:

package myPackage;import java.util.Scanner;public class ConverterMenu { public static void main(String[] args) {Scanner input = new Scanner(System.in);int option = 0;System.out.println("Do you want to convert hexadecimal to base 10, or the opposite? Please enter the corresponding number.");System.out.println("1) Hexadecimal to Base 10");System.out.println("2) Base 10 to Hexadecimal");while (option != 1&&option !=2){option = input.nextInt();if (option == 1){//Beginning of conversionString letter = new String();double finalAmount = 0;double amountOL;System.out.println("How many numbers/letters are in your hexadecimal number?");amountOL = input.nextDouble();for (double digit = 1; digit <= amountOL;digit++){System.out.println("What is the first/next number/letter?");letter = input.next();double power = amountOL - digit;if (letter == "0"){finalAmount = finalAmount + (0.0 * Math.pow(16.0, power));}if (letter == "1"){finalAmount = finalAmount + (1.0 * Math.pow(16.0, power));}if (letter == "2"){finalAmount = finalAmount + (2.0 * Math.pow(16.0, power));}if (letter == "3"){finalAmount = finalAmount + (3.0 * Math.pow(16.0, power));}}System.out.println(finalAmount);//End of conversion}if (option == 2){//Beginning of conversionSystem.out.println("2");//End of conversion}}input.close();} }
This is the console output and my input, green is me, blue is the console:
 
Do you want to convert hexadecimal to decimal, or the opposite? Please enter the corresponding number.
1) Hexadecimal to Decimal
2) Decimal to Hexadecimal

1
How many numbers/letters are in your hexadecimal number?
3
What is the first/next number/letter?
3
What is the first/next number/letter?
3
What is the first/next number/letter?
3
0.0
 
Why did the console return 0.0?
I was hoping for 819.0, so what went wrong?
Link to comment
https://linustechtips.com/topic/267158-new-java-programmer-massively-confused/
Share on other sites

Link to post
Share on other sites

Just to make it easier for me to read: 

package myPackage;import java.util.Scanner;public class ConverterMenu { public static void main(String[] args) {Scanner input = new Scanner(System.in);int option = 0;System.out.println("Do you want to convert hexadecimal to base 10, or the opposite? Please enter the corresponding number.");System.out.println("1) Hexadecimal to Base 10");System.out.println("2) Base 10 to Hexadecimal");while (option != 1&&option !=2){option = input.nextInt();if (option == 1){      String letter = new String();     double finalAmount = 0;     double amountOL =0;     System.out.println("How many numbers/letters are in your hexadecimal number?");     amountOL = input.nextDouble();     for (double digit = 1; digit <= amountOL;digit++){           System.out.println("What is the first/next number/letter?");            letter = input.next();           double power = amountOL - digit;           if (letter.equals("0"))                 finalAmount = finalAmount + (0.0 * Math.pow(16.0, power));           else if (letter.equals("1"));                 finalAmount = finalAmount + (1.0 * Math.pow(16.0, power));           else if (letter.equals("2"));                  finalAmount = finalAmount + (2.0 * Math.pow(16.0, power));          else if (letter.equals("3"));               finalAmount = finalAmount + (3.0 * Math.pow(16.0, power));    }    System.out.println(finalAmount);}  if (option == 2){//Beginning of conversionSystem.out.println("2");//End of conversion}}input.close();} }
You can't use == for strings. you have to use .equals()

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

You can't use == for strings. you have to use .equals()

 

You can, but it will be a reference equality rather than value equality.

String stringOne = "string";String stringTwo = stringOnestringOne == stringTwo // truestringOne.Equals(stringTwo) // trueString stringOne = "string";String stringTwo = "string";stringOne == stringTwo // falsestringOne.Equals(stringTwo) // true

@AnonymousUser52

Not sure if the lack of indentation in the OP is due to not having indentation or the formatting being messed up before you added the code tags, but make sure you're properly indenting your code.

"amountOL" isn't a very descriptive variable name, try renaming it

You could also replace the if statement with a switch statement, that can work out neater in some cases.

A better way to do this would be to try to parse the user's input into a number and check if it is within the 0 to 3 range.

try{    int inputtedNumber = Integer.ParseInt(input.next);    if(inputtedNumber >= 0 && inputtedNumber <= 3)    {        finalAmount += inputtedNumber * Math.pow(16.0, power));    }    else    {        System.out.println("The number needs to be between 0 and 3, try again!");    }}catch(NumberFormatException){    System.out.println("That wasn't a number, try again!");}

Not sure if at this stage you have seen try/catch blocks or exceptions at all, but they're worth looking up. The advantages of this solution is that you don't have that giant if statement so it is more readable and if the user enters invalid data they get warned about it.

Notice also that I've used "+=". At the compiler level, "x += 1" is the same as typing "x = x + 1" so there's no performance change in using this, but it is more readable.

 

Another issue I can see is that you're unnecessarily initialising variables before you use them

String letter = new String();// snip..letter = input.next // inside a for loop

This can be simplified to "String letter = input.next;". There's no need to initialise the string where you do since you never use the value. Also worth noting here is the scope of letter is wider than it needs to be. Not sure if you'll have met the idea of scope yet either, but basically a variable has a "scope" which determines where it can be used. If you declare a variable in the class (not in a method or anything) you can use it anywhere in that class, this is called a global variable and they are generally bad (not going to go into detail unless you want me to). If you declare a variable within a method it can only be accessed from within that method, same for variables declared within an if statement only being usable within that if statement.

The issue here is that letter should only be accessible within the for loop so you should declare it within that loop.

 

 

Another thing to note is that your program flow seems a bit out of place with how you get the options from the user. It isn't clear at first exactly how the while loop is entered or how the inner if statements are entered and it seems to only depend on the value of option being initialised as 0 at first.

A better way of going about this is to separate the input from the program logic as much as possible, i.e.

// All your system prints hereint option = input.nextInt();while (option != 1 && option != 2){    System.out.println("That isn't a valid option!");    // Print out options again    option = input.nextInt();}if (option == 1){}else if(option == 2){}

And lastly, it would be better to split your program logic up into separate methods, e.g. here you could have:

public static int ConvertHexadecimalToDecimal(Scanner input){    String letter = new String();    double finalAmount = 0;    double amountOL;    System.out.println("How many numbers/letters are in your hexadecimal number?");    amountOL = input.nextDouble();    for (double digit = 1; digit <= amountOL;digit++)    {        System.out.println("What is the first/next number/letter?");        letter = input.next();        double power = amountOL - digit;        if (letter == "0")        {            finalAmount = finalAmount + (0.0 * Math.pow(16.0, power));        }        if (letter == "1")        {            finalAmount = finalAmount + (1.0 * Math.pow(16.0, power));        }        if (letter == "2")        {            finalAmount = finalAmount + (2.0 * Math.pow(16.0, power));        }        if (letter == "3")        {            finalAmount = finalAmount + (3.0 * Math.pow(16.0, power));        }    }    return finalAmount;}

This makes your program much easier to read and maintain.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×