Java临时转换程序。正确输出但错误

时间:2016-11-12 07:19:53

标签: java string debugging

我不确定我做错了什么,分配是创建一个代码,将温度从C转换为F或从F转换为C直到用户决定它们完成,我也应该打印如果出现无效字符并让用户更正它而不再请求数字部分,则会显示错误消息。

程序似乎运行正常,直到我输入“c”C“f”或“F”以外的值。此时我仍然得到了所需的输出,但我得到的错误是我的代码。

import java.util.Scanner;

public class ProjectThree 
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter a temperature to be converted followed"
            + "\nby a C or c for Celsius or an F or f for Fahrenheit. If "
            + "\nfinished converting temperatures enter done.");
        String userInput, intString;
        userInput = keyboard.nextLine();

        while (!(userInput.equalsIgnoreCase("done")))
        {
            int length, temp, degreesC, degreesF;
            length = userInput.length();
            intString = userInput.substring(0,length - 1);
            temp = Integer.parseInt(intString);
            char scale = userInput.charAt(length - 1);

            while (!((scale == 'c') || (scale == 'C') || (scale =='f') || 
                (scale == 'F')))
            {
                System.out.println("Error: Invalid temperature unit. Enter a C or c"
                    + " for Celsius or an F or f for Fahrenheit.");
                String errorInput = keyboard.next();
                scale = errorInput.charAt(0);
                userInput = intString + errorInput;
            }
            switch (scale)
            {
                case 'C':
                case 'c':
                    degreesF = (9 * (temp / 5) + 32);
                    System.out.println(userInput + " is equal to " + degreesF 
                        + "F");
                    break;
                case 'F':
                case 'f':
                    degreesC = (5 * (temp - 32)) / 9;
                    System.out.println(userInput + " is equal to " + degreesC 
                        + "C");
                    break;
            }
            System.out.println("\nPlease enter a temperature to be converted followed"
                + "\nby a C or c for Celsius or an F or f for Fahrenheit. If "
                + "\nfinished converting temperatures enter done.");
            userInput = keyboard.nextLine();
        }
    }
}

,错误是

Please enter a temperture to be converted followed
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
by a C or c for Celsius or an F or f for Farenheit. If 
finished converting tempertures enter done.
    at java.lang.String.substring(String.java:1955)
    at ChapterFour.ProjectThree.main(ProjectThree.java:33)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)

2 个答案:

答案 0 :(得分:0)

总的来说,有很多东西可以"可以"输入错误会出错,因为您没有任何错误检查。以下是我注意到的一些事情......

1)正如我想其他人提到的那样,在你采取行动之前,你并没有检查任何输入的长度。如果有人在没有任何其他情况下进入,你可能会遇到异常。如果输入无效输入则相同。

2)switch语句缺少default子句。你应该添加打印出来的东西"出了点问题,请再试一次"只是让你知道它发生了。

3)当你只询问角色时,我看到你最初使用keyboard.nextLine()和keyboard.next()。如果在字符后面输入一个返回值,那么换行符可能会被下面的nextLine()拾取,这会导致如上面1中所述打印错误。谷歌搜索next()的行为以确认这一点,我发现以下(看起来像其他人有类似的问题):

Issues with nextLine();

答案 1 :(得分:0)

对于长度为one的空字符串或字符串,您没有处理任何内容。因此throw exception。您需要使用try catch阻止或执行操作像我这样的事情。我只是忽略输入字符串的长度zeroone

Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter a temperature to be converted followed"
                + "\nby a C or c for Celsius or an F or f for Fahrenheit. If "
                + "\nfinished converting temperatures enter done.");

        String userInput, intString;
        userInput = keyboard.nextLine();

        while (!(userInput.equalsIgnoreCase("done"))) {
            int length, temp, degreesC, degreesF;
            length = userInput.length();
            System.out.println(length);
            if (length > 1) {
                intString = userInput.substring(0, length - 1);
                temp = Integer.parseInt(intString);
                // System.out.println("Temp = " + temp);
                char scale = userInput.charAt(length - 1);
                // System.out.println("scale" + scale);

                while (!((scale == 'c') || (scale == 'C') || (scale == 'f') || (scale == 'F'))) {
                    System.out.println("Error: Invalid temperature unit. Enter a C or c"
                            + " for Celsius or an F or f for Fahrenheit.");
                    String errorInput = keyboard.next();
                    scale = errorInput.charAt(0);
                    userInput = intString + errorInput;
                }
                switch (scale) {
                case 'C':
                case 'c':
                    degreesF = (9 * (temp / 5) + 32);
                    System.out.println(userInput + " is equal to " + degreesF + "F");
                    break;
                case 'F':
                case 'f':
                    degreesC = (5 * (temp - 32)) / 9;
                    System.out.println(userInput + " is equal to " + degreesC + "C");
                    break;
                }
            }

            System.out.println("\nPlease enter a temperature to be converted followed"
                    + "\nby a C or c for Celsius or an F or f for Fahrenheit. If "
                    + "\nfinished converting temperatures enter done.");
            userInput = keyboard.nextLine();
        }

请注意 String substring(int beginIndex, int endIndex):从给定的substring开始,直到指定的index(beginIndex),返回index(endIndex)。对于例如&#34; Chaitanya&#34;。substring(2,5)将返回&#34; ait&#34;。它会引发IndexOutOfBoundsException如果beginIndex 小于零,或者beginIndex > endIndexendIndex大于length的{​​{1}}。< /强>

在您的情况下,如果您只是Stringc lenght-1成为C zero,那么您的last index也是{{} 1}}。这就是你获得first index的原因。

希望你明白了。