gpt4 book ai didi

java - 数组查找与输出

转载 作者:行者123 更新时间:2023-12-01 07:23:56 25 4
gpt4 key购买 nike

此代码有两个问题我无法纠正。

  1. 搜索 Entree:我不确定为什么它不允许用户通过控制台输入内容。我也不确定该部分的 for 循环是否正确。 (假设用户搜索主菜,并打印出该食物是哪一天。

  2. 最高价格:这部分代码唯一的问题是,无论最高价格如何,代码总是打印出最后输入的食物。

代码:

String[] daysOfTheWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
String[] foods = new String [5];
double[] prices = new double [5];

//What is being served?

Scanner keyboard = new Scanner(System.in);

for (int i = 0; i < daysOfTheWeek.length; i++) {
System.out.println("What entree is being served on " + daysOfTheWeek[i]);
foods[i] = keyboard.nextLine();
//Price of items
}

for (int i = 0; i < foods.length; i++) {
System.out.println("What is the price on " + foods[i]);
prices[i] = keyboard.nextDouble();
}

//Search for Entree
String answer;

System.out.println("What food would you like to search for?");
answer = keyboard.nextLine();

for (int i = 0; i < foods.length; i++) {
if (answer == foods[i])
System.out.println("This food item will be served on + daysOfTheWeek[i] ");
}

//Highest Price

double highest = prices [0];
int position = 0;

for (int i = 0; i < prices.length; i++) {
if (prices[i] > highest)
highest = prices[i];
position = i;
}
System.out.println("The highest price item was " + foods[position]);

最佳答案

关于你的第一个问题:在互联网上搜索如何在 Java 中比较字符串(提示:使用 == 不是你想要做的)。

关于第二个问题:

if(prices[i] > highest)
highest = prices[i];
position = i;

尝试添加大括号;-)

if(prices[i] > highest) {
highest = prices[i];
position = i;
}

关于java - 数组查找与输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29210929/

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