0

I have this following java program which is working fine without while loop, but I want to run the execution until user pressed Q key from the keyboard.

So What condition should be put in while loop which breaks the loop?

import java.awt.event.KeyEvent;
import java.util.Scanner;
import static javafx.scene.input.KeyCode.Q;

public class BinaryToDecimal {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);        
        while(kbhit() != Q){
            System.out.print("Input first binary number: ");
            try{          
                String n = in.nextLine();
                System.out.println(Integer.parseInt(n,2));
            }
            catch(Exception e){
                System.out.println("Not a binary number");
            }
        }
    }
}

Any help would be great. Thank You.

2 Answers2

3

I don't think you can use KeyEvent within a console application as there's no keyboard listener defined.

Try a do-while loop to watch for an input of the letter q. And you should compare strings using equals method

    Scanner in = new Scanner(System.in);        
    String n;
    System.out.print("Input first binary number: ");
    do {
        try{          
            n = in.nextLine();
            // break early 
            if (n.equalsIgnoreCase("q")) break;
            System.out.println(Integer.parseInt(n,2));
        }
        catch(Exception e){
            System.out.println("Not a binary number");
        }
        // Prompt again 
        System.out.print("Input binary number: ");
    } while(!n.equalsIgnoreCase("q"));
OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
0

What about this?

public class BinaryToDecimal {
    public static void main(String[] args) {
        System.out.print("Input first binary number: ");
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();
        while(!"q".equalsIgnoreCase(line.trim())){
            try{
                System.out.println(Integer.parseInt(line,2));
                System.out.print("Input next binary number: ");          
                line = in.nextLine();
            }
            catch(Exception e){
                System.out.println("Not a binary number");
            }
        }
    }
}
P3trur0
  • 2,887
  • 1
  • 11
  • 26