2

I'm writing a java program that translates hexadecimal into decimal and I ran into a problem with my while loop. I want it to break when the user types "break" into the console (I'm using Eclipse). I think it breaks the loop, but it continues with the last loop before stopping. I think I am using the right function, and if I understand correctly it should stop the code there and break.

Ignoring any other issues you might see in this code (I haven't coded in a while and thought this might be a fun challenge), what might be causing this?

package hex;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class HexConverter {
    
    public static HashMap<Character, Integer> conversion = new HashMap<Character, Integer>();
    public static char[] hex = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'  
    };
    static {
        for(int i = 0; i < 16; i++) {
            conversion.put(hex[i], i);
        }
        System.out.println(conversion);
    }
    
    public static void main(String[] args) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while(true) {
            String hex = "";
            try {
                hex = in.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(hex == "quit") {
                break;
            }
            System.out.println("didn't quit :(");
            int out = 0;
            for(int i = 0; i < hex.length(); i++) {
                out += ((int)conversion.get(hex.toUpperCase().toCharArray()[(hex.length() - 1) - i])) * Math.pow(16, i);
            }
            System.out.println(out);
        }
    }
}

2 Answers2

2

You should test Strings for equality using equals(), not ==.

if ("quit".equals(hex)) {

Expression hex.equals("quit") is correct too, it's good convention to prefer constant.equals(variable) form for better null safety.

Also note, you specified

I want it to break when the user types "break" into the console

but you are comparing the variable hex against a different string. The code above will break (i.e. get out of the loop) if the user types "quit" and not "break".

Simran Sharma
  • 852
  • 7
  • 16
Tomáš Záluský
  • 10,735
  • 2
  • 36
  • 64
0

Your problem in the equality, it is doing a equality by reference and not by value. You should use hex.equals("quit") instead, it will solve your problem

ENA
  • 13
  • 3