我应该制作一个程序,持续接受办公 table 订单数据并显示超过 36 英寸长且至少有一个抽屉的橡木办公 table 的所有相关信息。
import java.util.*;
public class MangMaxB
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
char ans;
int orderNum=0, length=0, width=0, numDrawer=0, price=1000;
String name;
System.out.print("Do you wish to enter Oak " +
"desk order data? (y/n)");
ans = input.nextLine().charAt(0);
while (ans != 'n')
{
System.out.print("Enter customer name: ");
name=input.nextLine();
System.out.print("Enter order number: ");
orderNum=input.nextInt();
System.out.print("Enter length and width of Oak desk" +
" separated by a space: ");
length = input.nextInt();
width = input.nextInt();
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
if ((length>36)&&(numDrawer>=1))
{
if ((length*width)>750)
{
price+= 250;
}
price+= (numDrawer*100);
price+= 300;
System.out.println("\nOak desk order information:\n"
+ "Order number: " + orderNum + "\n"
+ "Customer name: " + name + "\n"
+ "Length: " + length + ", width: "
+ width + ", surface: " + (length*width)
+ "\n" + "Number of drawer/s: " + numDrawer
+ "\nPrice of the desk is P " + price);
}
else
{
System.out.println("\nOak desk order isn't over 36 " +
"inches long and doesn't have a drawer");
}
System.out.print("Any more items? (y/n) ");
ans = input.nextLine().charAt(0);
}
}
}
我能够输入数据并显示它,但在第二次尝试时,因为它是一个循环,它没有工作。
它说“线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0 在 java.lang.String.charAt(未知来源) 在 controlStruc.MangMaxB.main"
我该如何解决这个问题?
最佳答案
nextInt()
不读取行尾 - 只读取下一个整数。如果您想阅读该行的剩余部分,您需要在 nextInt()
之后调用 nextLine()
。
目前你并没有这么做,所以最后一个nextLine()
方法只是读取了整数后面的空行,立即返回一个空字符串,导致异常.
在这种情况下,在这里调用 nextLine()
应该可以解决问题:
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
input.nextLine(); //Added nextLine() call
关于java - 循环不执行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15973942/