我正在尝试编写一个Java程序,用户在该程序中输入代表二进制数(0和1)的字符串。程序应验证输入是否为二进制数,如果不是这种情况,则程序将显示一条消息,指出该数字不是有效的二进制数。如果用户输入可接受,则程序应计算该单词中有多少个1,然后输出计数。
这是我到目前为止的内容,但是当我输入“ 1234”之类的字符串并转到第三个while循环时,它只会不断重印消息“您的数字只能包含一和零。请只包含一个二进制值一和零:“,即使我输入的有效字符串如” 0010“。我已经为此花了几天的精力,因此,非常感谢您的协助。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
System.out.println("Welcome to the binary scanner!");
System.out.print("Please enter a string in binary fashion: ");
while (!scan.hasNextInt()) {
System.out.println("That's not a binary number...\nPlease enter a binary number");
String temp = scan.nextLine();
}
input = scan.nextLine();
input = input.trim();
while (!input.contains("1")){
System.out.println("Your number does not contain any ones.\nPlease enter a binary number that contains ones.");
input = scan.nextLine();
}
while (input.contains("2") || input.contains("3") || input.contains("4") || input.contains("5") || input.contains("6") || input.contains("7") || input.contains("8") || input.contains("9")){
System.out.println ("Your number can only contain ones and zeros.\nPlease ever a binary value containing only ones and zeros: ");
input = scan.nextLine();
}
while (input.contains("1")){
boolean notOne = false;
int oneCount = 0;
for (int x = 0; x < input.length(); x++){
char c = input.charAt(x);
if (c == '1' || c == '0'){
if (c == '1'){
oneCount++;
notOne = true;
}
}
else {
notOne = false;
}
}System.out.println("The binary string contains " + oneCount + (oneCount == 1 ? " one." : " ones."));
break;
}
}
}
答案 0 :(得分:0)
欢迎使用Stackoverflow。我无法重现您的问题(我先输入1234,然后输入0010,效果很好)。但是,由于您的最后一个while循环无用,因此我对您的代码进行了一些修改。请尝试使用“调试器”来识别您的问题,或发布一些屏幕截图以证明您的问题。
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the binary scanner!");
System.out.print("Please enter a string in binary fashion: ");
while (!scan.hasNextInt())
{
System.out.println("That's not a binary number...\nPlease enter a binary number");
String temp = scan.nextLine();
}
String input = scan.nextLine();
input = input.trim();
while (!input.contains("1"))
{
System.out.println("Your number does not contain any ones.\nPlease enter a binary number that contains ones.");
input = scan.nextLine();
}
while (input.contains("2") || input.contains("3") || input.contains("4") || input.contains("5") || input.contains("6") || input.contains("7") || input.contains("8") || input.contains("9"))
{
System.out.println("Your number can only contain ones and zeros.\nPlease ever a binary value containing only ones and zeros: ");
input = scan.nextLine();
}
int oneCount = 0;
for (int x = 0; x < input.length(); x++)
{
char c = input.charAt(x);
if (c == '1')
{
oneCount++;
}
}
System.out.println("The binary string contains " + oneCount + (oneCount == 1 ? " one." : " ones."));
}