import java.util.Scanner;
import java.text.DecimalFormat;
public class palomba2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
//allows input to be read
// VOLUME OF A PRISM
int prLngth, prWdth, prHght, prVol;
System.out.print("Enter the length of the prism in feet: ");
prLngth = keyboard.nextInt();
System.out.print("Enter the width of the prism in feet: ");
prWdth = keyboard.nextInt();
System.out.print("Enter the height of the prism in feet: ");
prHght = keyboard.nextInt();
prVol = prLngth * prWdth * prHght;
System.out.print("The volume of the prism is " + prVol);
System.out.print(" feet.");
System.out.println("");
System.out.println("");
// AREA/CIRCUMFERENCE OF A CIRCLE
DecimalFormat format = new DecimalFormat("0.##");
double radius, circ, area;
System.out.print("Enter the radius of a circle rounded to the nearest hundreth: ");
radius = keyboard.nextInt();
circ = 2 * radius * 3.14159265358979;
area = radius * radius * 3.14159265358979;
System.out.print("The circumference of the circle is " + format.format(circ));
System.out.print("units.");
System.out.print("The area of the circle is " + format.format(area));
System.out.print("units.");
}
}
我的代码中的所有内容都会起作用,直到我输入圆的半径为止。输入半径后,它会出现错误消息。
Enter the radius of a circle rounded to the nearest hundreth: 2.12
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:860)
at java.base/java.util.Scanner.next(Scanner.java:1497)
at java.base/java.util.Scanner.nextInt(Scanner.java:2161)
at java.base/java.util.Scanner.nextInt(Scanner.java:2115)
at palomba2.main(palomba2.java:52)
答案 0 :(得分:3)
您键入了一个双变量2.12
,但尝试将其读作int
:输入不匹配 - > InputMismatchException
此外,变量radius
的类型为double
,因此您无法为其赋予int
值(您也需要:
radius = keyboard.nextDouble();
但更好的方法是使用radius = Double.parseDouble(keyboard.nextLine())
来使用返回字符(int
也是如此:int val = Integer.parseInt(keyboard.nextLine())
答案 1 :(得分:0)
您只需要更改:
radius = keyboard.nextInt();
为:
radius = keyboard.nextDouble();
因为变量radius
被声明为double
它应该是这样的:
double radius, circ, area;
System.out.print("Enter the radius of a circle rounded to the nearest hundreth: ");
radius = keyboard.nextDouble();