简体   繁体   English

Java程序不会停止接受用户输入

[英]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. 我正在编写一个Java程序,该程序从用户处获取一个整数并以二进制形式输出该数字。 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. 该程序要求用户输入一个数字,但是当我按Enter键时,它仅转到下一行,用户可以无限输入。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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