gpt4 book ai didi

java - 从多个不同类型的用户输入创建一个数组

转载 作者:搜寻专家 更新时间:2023-11-01 01:08:14 25 4
gpt4 key购买 nike

我如何将用户输入项目(名称、成本、优先级)中的 3 个项目放入一个对象项目中,并将该对象项目放入其他对象的数组中?

public class Main {

public static void main(String[] args) {
//here are my variables.
//I'm pretty sure a few of these should be defined
// in their own item class.
int i=0;
String name1;
int priority1;
double cost1;

//String[] shoppingList = new String[7];
String[] item = new String[7];

// I am able to grab input from the user for all 3 elements of
// an item object (name, cost, priority)
// I am missing how to save these 3 elements into an item object
// and create an array for each item object
for (i=0; i<item.length;i++) {

//I want to capture name, priority, and cost of each item
// and add each item as an in
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();

Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();

Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();

最佳答案

“我如何将用户输入项目(名称、成本、优先级)中的 3 个项目放入一个对象项目中”

如果我没理解错的话,解决办法是创建一个新类。调用它与你正在做的事情相关

class Data {
String name;
double cost;
int priority;
Data(String name, double cost, int priority) { //Set variables }
}

然后您可以使用您的相关信息创建一个新的“数据”类:

Data myObject = new Data("Input1", 37.50, 2);

例如,随机信息。您可以根据需要制作任意数量的这些独特对象,并根据您的需要将它们添加到数组或 ArrayList 中:

Data[] myArray = new Data[100];
//or
List<Data> myList = new ArrayList<Data>();

关于java - 从多个不同类型的用户输入创建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17736885/

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