我是一名学生,我的任务是编写一个程序,该程序接受三角形的三个边,并输出三角形相对于边的角度。我还没有编写方程式,但是我一直在使用Scanner和“ if”语句来启动程序。我已经遇到了问题:
-这是程序开头部分的输出。但这就是停止的地方。我提示用户键入“ D”或“ R”,并且不允许用户在该位置键入。但是,在程序的前面,我能够提示用户输入字符。有人可以弄清楚为什么上一个提示起作用而该提示不起作用吗?-
这是SSS Triangle程序,用于查找三角形的角度。 您知道三角形的所有边但需要知道角度吗? (是/否):是
三角形的边长是多少? -如果长度相同,则不必担心最小,中等和最大的长度- 最小边长: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();
答案 0 :(得分:0)
将最后一个else语句更改为read.next()并执行代码。您只是想获得一个String响应,因此无需从Scanner抓起整行:
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
答案 1 :(得分:-1)
问题在于该程序实际上确实读取了一行然后退出。之所以找到某种东西,是因为当您阅读最后一个双精度字时,用户输入了换行符,但从未读取过(因为您只读取了双精度字)。要解决此问题,除了当前的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();