import java.util.Scanner;
class Quiz4 {
public static void main(String args[]){
char repeat = userInput.charAt(0);
do{
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number ");
String binaryString =input.nextLine();
if (binaryString.matches("[10]+")) {
System.out.println ("You entered " +binaryString );
System.out.println("Its base of 10 equivalent is "+Integer.parseInt(binaryString,2));
} else {
System.out.println ("Try again ");
}while (repeat == 'Y' || repeat == 'y');
}
}
}
我正在编写一个将二进制转换为十进制的代码,除了我必须确保程序继续工作直到用户提示它停止之外,我已经完成了所有工作。我不知道如何将它应用于我的代码。我知道我使用了do / while循环,但我不知道如何应用它。
import java.util.Scanner;
class Quiz4 {
public static void main(String args[]){
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number ");
String binaryString =input.nextLine();
if (binaryString.matches("[10]+")) {
System.out.println ("You entered " +binaryString );
System.out.println("Its base of 10 equivalent is "+Integer.parseInt(binaryString,2));
} else {
System.out.println ("Try again ");
}
}
}
答案 0 :(得分:0)
您的代码中存在2个问题。 1)重复不会在循环中改变,因此循环将永远循环或仅运行一次。要解决此问题,在循环中的某个时刻,您需要将repeat更改为用户在被问及是否要继续进行时的最后响应。这让我想到2)你永远不会问用户他们是否想再次转换。询问用户是否要继续使用,指定他们必须回答Y或y,然后将他们的回复存储在重复
答案 1 :(得分:-1)
使用do while循环
import java.util.Scanner;
class Main {
public static void main(String args[]){
Scanner input = new Scanner( System.in );
String str;
do{
System.out.println("Enter a binary number ");
String binaryString =input.nextLine();
if (binaryString.matches("[10]+")) {
System.out.println ("You entered " +binaryString );
System.out.println("Its base of 10 equivalent is "+Integer.parseInt(binaryString,2));
} else {
System.out.println ("Try again ");
}
System.out.println("Do you want to continue ? Press Y or y");
str = input.nextLine();
}while(str.charAt(0) == 'Y'||str.charAt(0) == 'y');
System.out.println("Exiting");
}
}
在控制台上输出。
Enter a binary number
100
You entered 100
Its base of 10 equivalent is 4
Do you want to continue ? Press Y or y
y
Enter a binary number
102
Try again
Do you want to continue ? Press Y or y
y
Enter a binary number
111
You entered 111
Its base of 10 equivalent is 7
Do you want to continue ? Press Y or y
Y
Enter a binary number
110
You entered 110
Its base of 10 equivalent is 6
Do you want to continue ? Press Y or y
n
Exiting