该程序要求我要求用户输入菜单项及其价格,并一直这样做,直到用户输入 0。然后用户将输入“1”以查看菜单项和价格的列表。这是代码:
import java.util.*;
import java.io.*;
public class Restaurant Trial {
final static int Max=100;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[]item_name=new String[Max];
double[]item_price=new double[Max];
int totalitems=0;
int n=0;
String trap;
System.out.printf("\nEnter the name of item followed by its price: \nEnter '0' to stop\n");
String name=in.nextLine();
trap = in.nextLine();
double price=in.nextDouble();
while (name!="") {
totalitems++;
item_name[n++]=name;
item_price[n++]=price;
System.out.printf("\nEnter the name of item followed by its price: \nEnter '0' to stop\n");
trap=in.nextLine();
name=in.nextLine();
if ("0".equals(name))
break;
price=in.nextDouble();
}//end while
int lo=1;
System.out.printf("\nEnter 1 to view all menu items and prices\n" +
"Enter 2 to view the price of a menu item\n"+
"Enter 3 to edit the price of a menu item\n" +
"Enter 4 to add an item to the menu\n" +
"Enter 5 to exit the program\n");
int action = in.nextInt();
if (action==1) {
System.out.printf("MENU ITEM PRICE");
for (int l=1; l<=totalitems; l++) {
System.out.printf("\n%s $%3.2f", item_name[l], item_price[l]);
}
}
}//end main
当我输入“1”来打印输出时,问题就来了。以下是输出示例:
Enter the name of item followed by its price:
Enter '0' to stop
chicken
3.50
Enter the name of item followed by its price:
Enter '0' to stop
rice
4.90
Enter the name of item followed by its price:
Enter '0' to stop
fish
12.9
Enter the name of item followed by its price:
Enter '0' to stop
pasta
13.45
Enter the name of item followed by its price:
Enter '0' to stop
0
Enter 1 to view all menu items and prices
1
MENU ITEM PRICE
null $3.50
rice $0.00
null $4.90
fish $0.00
Process completed.
哦,补充一下,我使用变量“trap”来尝试保存程序在我按 Enter 时输入的换行符。请,如果有人可以提供任何建议,将不胜感激。