gpt4 book ai didi

java - 数组中的所有其他值都打印为 Null

转载 作者:行者123 更新时间:2023-12-01 18:26:32 25 4
gpt4 key购买 nike

该程序要求我要求用户输入菜单项及其价格,并继续这样做,直到用户输入 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 时程序接收的换行符。请,如果有人可以提供任何建议,我们将不胜感激。

最佳答案

看起来是因为您在存储项目的两行上都递增了 n:

item_name[n++]=name;
item_price[n++]=price;

关于java - 数组中的所有其他值都打印为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25951783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com