无法从用户获取工作"calculate again"



我写了一个石头,纸,剪刀游戏,有一个再次播放的功能。

我不明白那里缺少什么。

我只需要它来询问用户是否要计算另一个圆。

代码片段:

package circleapp;
import java.util.Scanner;
public class CircleApp {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String answer;
String calcAgain;
do{
System.out.print("Enter a radius: ");
double radius = sc.nextDouble();
//Diameter=2 * radius
double diameter= 2 * radius;
System.out.println("Diameter: " + diameter);
//Circumference= 2 * PI * radius
double circumference= Math.PI * 2*radius;
System.out.println( "Circumference: "+circumference);
//Area= PI*radius*radius
double area = Math.PI * (radius * radius);
System.out.println("Area: " + area);

//Would the user like to calculate again?
System.out.print("Would you like to enter another circle? (Y/N)");
calcAgain = sc.nextLine();
}
while (calcAgain.equalsIgnoreCase("Y"));
}     
}

如何解决这个问题?

不要用nextLine()阅读整行,而是使用简单的next()

import java.util.Scanner;
public class CircleApp {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String calcAgain;
do {
System.out.print("Enter a radius: ");
double radius = sc.nextDouble();
//Diameter=2 * radius
double diameter = 2 * radius;
System.out.println("Diameter: " + diameter);
//Circumference= 2 * PI * radius
double circumference = Math.PI * 2 * radius;
System.out.println("Circumference: " + circumference);
//Area= PI*radius*radius
double area = Math.PI * (radius * radius);
System.out.println("Area: " + area);

//Would the user like to calculate again?
System.out.print("Would you like to enter another circle? (Y/N) ");
calcAgain = sc.next();
} while (calcAgain.equalsIgnoreCase("Y"));
}
}

输出将如下所示:

Enter a radius: 4
Diameter: 8.0
Circumference: 25.132741228718345
Area: 50.26548245743669
Would you like to enter another circle? (Y/N): y
Enter a radius: 5
Diameter: 10.0
Circumference: 31.41592653589793
Area: 78.53981633974483
Would you like to enter another circle? (Y/N): n

另外,我的建议是编写更具可读性的代码。例如,下面的内容将更适合阅读:

双周长 = 数学.PI*2*半径;

双周长 = 数学.PI * 2 * 半径;

顺便说一句,在这里提问时,只需指定您的问题并省略另一个细节。

更改

calcAgain = sc.nextLine();

calcAgain = sc.next();

这应该有效

相关内容

  • 没有找到相关文章

最新更新