gpt4 book ai didi

java - Java 中的转换程序错误

转载 作者:行者123 更新时间:2023-12-01 07:22:01 25 4
gpt4 key购买 nike

今天早上我很无聊,所以我决定制作一个程序,用户可以在其中转换速度、质量、温度或长度。我使用扫描仪和开关操作器来完成此操作。基本上,我让用户输入他们想要转换的内容,然后 switch 运算符根据答案运行某种方法。到目前为止,我只完成了弥撒,这就是为什么其他方法被注释掉的原因。代码和输出如下:

代码:

import java.util.Scanner;


public class Convertions {
public static void main(String[] args) {
System.out.println("Would you like to convert: Mass, Temperature,\nLength, or Speed?");
Scanner scan = new Scanner(System.in);
String answer = scan.nextLine().toUpperCase();
scan.close();
switch(answer) {
case "MASS":
massConvert();
break;
case "TEMPERATURE":
//tempConvert();
break;
case "LENGTH":
//lengthConvert();
break;
case "SPEED":
//speedConvert();
break;
default:
System.out.println("Please enter something else!");
}

}

public static double massConvert() {
Scanner scanMass = new Scanner(System.in);
System.out.println("1. kg to lbs\n2. lbs to kg");
int answerMass = scanMass.nextInt();
switch(answerMass) {
case 1:
System.out.println("Enter a value in kgs:");
int kiloMass1 = scanMass.nextInt();
scanMass.close();
int poundMass1 = (int)((int)kiloMass1 * 2.2046);
System.out.println(kiloMass1 + " kgs is equal to " + poundMass1 + " lbs");
break;
case 2:
System.out.println("Enter a value in lbs:");
int poundMass2 = scanMass.nextInt();
scanMass.close();
int kiloMass2 = (int)((int)poundMass2/2.2046);
System.out.println(poundMass2 + " lbs is equal to " + kiloMass2 + " kgs");
break;
}
return 0.0;
}
}

输出:

Would you like to convert: Mass, Temperature, 
Length, or Speed?
/*This wasn't in the output, but I just want to mention that the line with "Mass" was my input.*/
Mass
1. kg to lbs
2. lbs to kg
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Convertions.main(Convertions.java:14)

最佳答案

读取用户的第一个输入后,您将关闭链接到标准输入流的Scanner:

scan.close();

这会导致 stdin 关闭,并且输入流的任何后续使用都会失败并出现异常。

要解决此问题,您应确保仅在不需要更多输入时关闭扫描仪

关于java - Java 中的转换程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33972221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com