我编写了一个 Box
类,它有两个构造函数。一个是 Box()
,它是默认构造函数,当用户输入空格时执行,另一个是 Box(length, width, height)
,它是当用户实际上为给定框输入输入时执行。所以我用以下方式编写了类Box
:
class Box{
private int length, breadth, height;
//Default Constructor
Box(){
System.out.print("No Parameter given");
}
//Parameterized Constructor
Box(int l, int b, int h){
length=l; breadth=b; height=h;
}
int volume(){
return breadth*height*length;
}
}
所以,这是我尝试实现代码的 main()
函数。我的目的是当输入为空格时调用默认构造函数,如果输入不为空则通过第二个构造函数计算 voulme。
class mybox{
public static void main(String args[]) throws IOException{
System.out .print("Enter length, breadth and height->>");
Scanner scanner=new Scanner(System.in);
int length1=scanner.nextInt();
System.out.println("Length= "+length1);
int breadth1=scanner.nextInt();
System.out.println("Breadth= "+breadth1);
int height1=scanner.nextInt();
System.out.println("Height= "+height1);
if( length1== Integer.parseInt(" ")
&& breadth1== Integer.parseInt(" ")
&& height1== Integer.parseInt(" ") ){
Box samplebox=new Box();
}
else {
Box samplebox=new Box(length1, breadth1, height1);
try{
System.out.println("The volume of the box is " + samplebox.volume());
} catch (ArithmeticException e){
e.printStackTrace();
}
}
}
}
在 Eclipse 中,我在 Box Samplebox=new Box()
行中收到警告“未使用局部变量 Samplebox 的值”。那么代码中的错误在哪里呢?
最佳答案
scanner.nextInt()
不能接受空字符串输入。它将等待有效的数字/字符输入。
Integer.parseInt("")
将抛出异常,因为空格不是有效的整数字符串。
关于java - 为什么控件没有到达循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803839/