【发布时间】:2020-02-08 23:06:47
【问题描述】:
要求用户输入温度,然后用户输入一个数字,后跟 C 或 F 表示摄氏温度或华氏温度。然后程序会识别温度以及测量温度的单位 - 使用这些数据可以告诉您“水”是固态、液态还是气态。
我试过下面的
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
System.out.print("Enter THE temp: ");
String ent = myScan.next();
int temp = Integer.parseInt(ent.substring(0,4));
//char type = ent.charAt();
//System.out.println(temp);
// System.out.println(type);
if (temp >= 100) {
System.out.println("The water is gaseous");
} else if (temp < 0) {
System.out.println("The water is solid");
} else {
System.out.println("the water is liquid");
}
}
当我将 (0,4) 放在临时子字符串中时,我会认为输出将是输入的前 3 个数字。相反,当我输入 1 int 或 3 时,我得到一个错误“java.lang.StringIndexOutOfBoundsException”。
【问题讨论】:
-
从用户输入(通过
System.in)获取一行时,最好使用Scanner#nextLine(),因为这样会获取整行,而不是第一个标记。 -
btw @Kieron 你的测试数据是什么?