简体   繁体   中英

Java Program Won't Stop Accepting User Input

I'm writing a java program that takes an integer from the user and outputs that number in binary. My code does not give me any errors, but the program won't run like it should. The program asks for the user to input a number, but when I hit enter, it simply goes to the next line and the user can input infinitely. Where did I go wrong? I've tried debugging it but I can't seem to find the problem. Thank you so much in advance!

package example;
import java.util.Scanner;    
public class test {

public static void main(String[] args) {
    Scanner inScanner = new Scanner(System.in);
    int input = promptForDecimal(inScanner);
    String output = decimalToBinary(input);
    System.out.println("The decimal value " + input + " is " + output 
                    + " in binary.");
}

public static String decimalToBinary(int value) {
    String binary = "";
    int i = 0;
    while (value > 0) {
        i = value % 2;
        if (i == 1) {
            binary = binary + "1";
        }
        else {
            binary = binary + "0";
        }
    }
    return binary;
}


public static int promptForDecimal(Scanner inScanner) {
    System.out.print("Enter an integer value (negative value to quit): ");
    String val = inScanner.nextLine();
    while (checkForValidDecimal(val) == false)  {
        System.out.println("Error - value must contain only digits");
        System.out.println("Enter an integer value (negative value to quit): ");
        val = inScanner.nextLine();
    }
    return Integer.parseInt(val);
}


public static boolean checkForValidDecimal(String value) {
    int length = value.length();
    int pos = 0;
    boolean a = true;
    while (pos < length) {
        a = Character.isDigit(value.charAt(pos));
        if (a == true) {
            pos++;
        }
        else {
            if (value.charAt(0) == '-') {
                pos++;
            }
            else {
                a = false;
            }
        }

    }
    return a;
}
}   

You forgot to update your value after you write the binary out.

public static String decimalToBinary(int value) {
    String binary = "";
    int i = 0;
    while (value > 0) {
        i = value % 2;
        value = value / 2;
        if (i == 1) {
            binary = binary + "1";
        }
        else {
            binary = binary + "0";
        }
    }
    return binary;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM