gpt4 book ai didi

java - 如何创建一个数组,提示用户输入 taco 1 的名称,然后输入价格 1?

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

使用我当前拥有的代码,用户可以一次输入一个炸 Jade 米饼,但是当我运行它时,我将输入第一个炸 Jade 米饼的名称,然后自动列出价格“输入炸 Jade 米饼的价格” 1 到 10。如何解决这个问题。我确信在循环方面我做错了什么。

代码:

import java.util.Scanner;

public class TacoSort {
//Create a constant amount of temperatures
public static int NUMBER_OF_TACOS = 10;
public static int NUMBER_OF_PRICES = 10;
public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the taco price sorter! Enter 10 taco names and prices and I'll sort it!");

//Populates array of 10 tacos
//Prompts user to enter name of each taco
String[] tacos = new String[NUMBER_OF_TACOS];
for (int i = 0; i < NUMBER_OF_TACOS+1; i++)
{
System.out.print("Enter the name of taco " + (i+1) + "\n");
tacos[i] = keyboard.nextLine();

//Populates array of 10 prices
//Prompts user to enter price of each taco
double[] prices = new double[NUMBER_OF_PRICES];
for (int j = 0; j < NUMBER_OF_PRICES; j++)

System.out.print("Enter taco's price" + (j+1) + "\n");
System.out.println("\n");
prices[i] = keyboard.nextDouble();
}
}
}

用户输出应类似于:

Enter the name of taco 1
Crunchy Taco
Enter taco's price
1.19
Enter the name of taco 2
Crunchy Taco Supreme
Enter taco's price
1.59
Enter the name of taco 3
Soft Taco
Enter taco's price
1.19

最佳答案

我对炸 Jade 米饼不太了解(开玩笑,我真的很了解),但我注意到这里有一些错误的地方。

首先,你的 for 循环应该是:

for (int i = 0; i < NUMBER_OF_TACOS; i++) 

您原本有 i < NUMBER_OF_TACOS + 1 ,这会导致索引越界异常。

其次,您没有正确终止第一个 for 循环的括号;你缺少一个大括号。在第二个 for 循环条件之后,您还缺少一个起始大括号。

第三,您可能应该通过循环检查错误的用户输入,直到用户输入适当的值,并使用类型转换而不是 Scanner#nextDouble() .

最后,您将执行整个第一个循环,然后执行整个第二个循环。如果您希望程序询问 Taco #1 的名称和价格,然后询问 Taco #2 的名称和价格,依此类推,那么您应该在同一循环中询问每个 Taco 的名称和价格。

正确的代码如下所示:

import java.util.Scanner;

public class TacoSort {
//Create a constant amount of tacos
public static int NUMBER_OF_TACOS = 10;
public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the taco price sorter! Enter 10 taco names and prices and I'll sort it!");

//Populates array of 10 tacos
//Prompts user to enter name of each taco
String[] tacos = new String[NUMBER_OF_TACOS];
double[] prices = new double[NUMBER_OF_TACOS]; // NOTE Moved this up from below
for (int i = 0; i < NUMBER_OF_TACOS; i++) // NOTE Fixed off-by-one error
{
System.out.print("Enter the name of taco " + (i+1) + "\n");
tacos[i] = keyboard.nextLine();
System.out.print("Enter taco's price " + (i+1) + "\n");
prices[i] = keyboard.nextDouble(); // TODO Fix this so it checks for non-double input?
} // NOTE Added end-bracket here!

// Consolidated prices loop into taco names loop

// Do something with the list of tacos and prices
}
}

关于java - 如何创建一个数组,提示用户输入 taco 1 的名称,然后输入价格 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32745667/

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