このプログラムでは、ユーザーにメニュー項目とその価格を入力するように求め、ユーザーが 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 キーを押したときにプログラムが取り込む改行文字を保持しようとしました。どなたかアドバイスをいただければ幸いです。