该程序要求我要求用户输入一个菜单项及其价格并继续这样做,直到用户输入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时所接受的换行符。 如果有人可以提供任何建议,我们将不胜感激。
答案 0 :(得分:2)
看起来是因为您在存储项目的两行上递增n
:
item_name[n++]=name;
item_price[n++]=price;
答案 1 :(得分:2)
在这里,你要两次递增n
:
item_name[n++]=name;
item_price[n++]=price;
要修复,请将其更改为
item_name[n]=name;
item_price[n++]=price;