首页 > 解决方案 > Java 问题中的扫描器和用户输入

问题描述

我是一名学生,我的任务是编写一个程序,该程序接收三角形的三个边并输出三角形相对于边的角度。我还没有编写方程式,但我一直在搞乱扫描仪和“if”语句来启动程序。我已经有一个问题:

--这是程序开始部分的输出。但这就是它停止的地方。我提示用户输入“D”或“R”,但不允许用户在该位置输入。然而,在程序的早期,我能够提示用户输入一个字符。有人能弄清楚为什么前面的提示有效,而这个无效。--

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

你的三角形的边长是多少?- 如果长度都一样,那么不要担心最小、中等和最大- 最小边的长度: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();

标签: javajava.util.scanner

解决方案


将最后一个 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

推荐阅读