我應該製作一個程序,不斷接受桌面訂單數據並顯示超過36英寸長且至少有一個抽屜的橡木桌子的所有相關信息。循環不會執行一次以上
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」
我該如何解決這個問題?
爲什麼不只是處理'String'對象?沒有真正的要點將'char'從'String'中取出。無論如何,它看起來像它應該工作,你確定你問了一個字符嗎?如果您剛剛點擊輸入,那麼'String'的位置0處不會有'char'。 – Quetzalcoatl
好吧,在我看來,'input.nextLine()'是在你的循環結尾的空字符串 –
@SamIam它*爲什麼*它是一個空字符串,儘管這是真正的問題! – berry120