繁体   English   中英

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

[英]Java Program Won't Stop Accepting User Input

我正在编写一个Java程序,该程序从用户处获取一个整数并以二进制形式输出该数字。 我的代码没有给我任何错误,但是该程序无法正常运行。 该程序要求用户输入一个数字,但是当我按Enter键时,它仅转到下一行,用户可以无限输入。 我哪里做错了? 我尝试调试它,但是似乎找不到问题。 提前非常感谢您!

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;
}
}   

在写出二进制文件后,您忘记了更新值。

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