Java故障中的扫描仪和用户输入



我是一名学生,我的任务是制作一个程序,接收三角形的三条边,并输出三角形相对于边的角度。我还没有编程方程,但我一直在摆弄扫描仪和"如果"语句来启动程序。我已经有一个问题:

--这是程序开始部分的输出。但这就是它停止的地方。我提示用户键入"D"或"R",但它不允许用户在该位置键入。然而,在程序的早期,我能够提示用户输入一个字符。有人能理解为什么上一个提示有效,而这个提示无效吗?——

这是SSS三角形程序,用于查找三角形的角度。你知道三角形的所有边,但需要知道角度吗?(Y/N):Y

你三角形边的长度是多少?-如果长度相同,那么不要担心最小、中等和最大的-最小边的长度:3中边长度:4最长边的长度:5你想要以度还是弧度为单位的角度?(D/R):

--这是代码。最后一行是我遇到麻烦的地方——

public class SSSTriangle {
public static Scanner read= new Scanner(System.in);
public static void main(String[]args) {
System.out.print("This is the SSS Triangle program to find the angles of a triangle. n Do you know all the sides of a triangle but need to know the angles? (Y/N):");
String response= read.nextLine();
if (response.contains("N")) {
System.out.println("Okay, have a good day!");
}
if (response.contains("Y")) {
giveMeTheSides();
}
}
public static void giveMeTheSides() {
System.out.println("nWhat are the lengths of the sides of your triangle? n -If all the same length then don't worry about the smallest, medium, and largest-");
System.out.print("The length of the smallest side: ");
double a = read.nextDouble();
System.out.print("The length of the medium side: ");
double b = read.nextDouble();
System.out.print("The length of the longest side: ");
double c = read.nextDouble();
if (a<=0||b<=0||c<=0) {
System.out.println("Nice try! Your given sides do not produce a possible triangle.");
}
else {
if ((a+b)<c) {
System.out.println("Nice try! Your given sides do not produce a possible triangle.");       
}
else {
System.out.println("Would you like the angles in degrees or radians? (D/R): ");
String newResponse= read.nextLine();

将最后一条else语句更改为read.next(),然后执行代码。你只是想得到一个字符串响应,所以没有必要从扫描仪中获取整行:

else {
System.out.println("Would you like the angles in degrees or radians? (D/R): ");
String newResponse = read.next();//Change to read.next()
System.out.println("Your new response was " + newResponse); //Psuedo code to see if the output is correct. 
}

这是你的最后一行输出:

Would you like the angles in degrees or radians? (D/R): 
D
Your new response was D

问题是程序实际上读取了一行,然后退出。它找到了一些东西,因为当你读取最后一个双精度时,用户输入了一个换行符,但它从未被读取(因为你只读取双精度)。为了解决这个问题,除了当前的nextLine()之外,您还可以在nextDouble()之后读取另一行(带有额外的换行符)。

System.out.print("The length of the smallest side: ");
double a = read.nextDouble();
System.out.print("The length of the medium side: ");
double b = read.nextDouble();
System.out.print("The length of the longest side: ");
double c = read.nextDouble();
read.nextLine(); // Discard the extra newline
if (a<=0||b<=0||c<=0) {
...
else {
System.out.println("Would you like the angles in degrees or radians? (D/R): ");
String newResponse= read.nextLine();

相关内容

最新更新