java 从多个不同类型的用户输入创建一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17736885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating an Array from multiple user inputs of different types
提问by user2558595
How I would get the 3 items from user input Item (name, cost, priority) into one object item and place that object item into an array of other objects?
我如何将用户输入项(名称、成本、优先级)中的 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();
回答by Kon
"How I would get the 3 items from user input Item (name, cost, priority) into one object item"
“我如何将用户输入项目(名称、成本、优先级)中的 3 个项目放入一个对象项目中”
If I understand you correctly, the solution would be to make a new class. Call it whatever is relevant for what you're doing
如果我理解正确,那么解决方案是创建一个新类。将其称为与您正在做的事情相关的任何事情
class Data {
String name;
double cost;
int priority;
Data(String name, double cost, int priority) { //Set variables }
}
Then you can create a new "Data" class with your relevant information with:
然后您可以使用您的相关信息创建一个新的“数据”类:
Data myObject = new Data("Input1", 37.50, 2);
Just for example, with random information. You can make as many of these unique objects as you'd like, and add them to an array or ArrayList depending on what you want to do:
仅以随机信息为例。您可以根据需要制作任意数量的这些独特对象,并根据您的需要将它们添加到数组或 ArrayList 中:
Data[] myArray = new Data[100];
//or
List<Data> myList = new ArrayList<Data>();
回答by Doorknob
You could try a custom class:
您可以尝试自定义类:
public class Item {
private String name;
private double price; // you should probably use an 'int' for this
// it would be the amount of cents
// that would avoid rounding errors
private int priority;
public Item(String name, double price, int priority) {
this.name = name;
this.price = price;
this.priority = priority;
}
// (getters and setters)
public String getName() {
return name;
}
...
}
Item milk = new Item("milk", 19.99, 3); // wow, expensive milk :P
Item[] items = [milk, new Item("cheese", 99.99, 2), ...];
回答by Brandon Damante
What you could do is create a class, and use the constructor to help pass parameters. You could then make an instance of this class, and use it to set the parameters to whatever you need (i.e the name, price, etc.). Then accept the user input using the Scanner
, and what I would do, is make an ArrayList
of (I'll call it ItemData). Then, add the instance to the ArrayList
using .add(this)
. Here's the code for each step:
您可以做的是创建一个类,并使用构造函数来帮助传递参数。然后,您可以创建此类的一个实例,并使用它来将参数设置为您需要的任何内容(即名称、价格等)。然后使用 接受用户输入Scanner
,我会做的是制作一个ArrayList
(我将其称为 ItemData)。然后,将实例添加到ArrayList
using .add(this)
。这是每个步骤的代码:
Pass the parameters in the constructor:
public class ItemData{ public ItemData(String name, double cost, int priority){ } }
Make a new instance of
ItemData
in theMain
class at the end of the input:ItemData itemData = new ItemData(name, cost, priority);
Make the
ArrayList
field (make sure you importjava.util.ArrayList
andjava.util.List
) :List<ItemData> dataStorage = new ArrayList<ItemData>();
Add the instance of
ItemData
to theArrayList
into theItemData
constructor:Main.(ArrayList name here).add(this);
在构造函数中传递参数:
public class ItemData{ public ItemData(String name, double cost, int priority){ } }
在输入的末尾
ItemData
在Main
类中创建一个新实例:ItemData itemData = new ItemData(name, cost, priority);
制作该
ArrayList
字段(确保您导入java.util.ArrayList
和java.util.List
):List<ItemData> dataStorage = new ArrayList<ItemData>();
添加实例
ItemData
到ArrayList
到ItemData
构造函数:Main.(ArrayList name here).add(this);
Your final code should look like this:
您的最终代码应如下所示:
public class ItemData{
public ItemData(String name, double cost, int priority){
Main.itemData.add(this);
}
}
import java.util.*;
public class Main {
public static List<ItemData> itemData = new ArrayList<ItemData>();
public static void main(String[] args) {
int i=0;
String name1;
int priority1;
double cost1;
String[] item = new String[7];
for (i=0; i<item.length; i++) {
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();
ItemData x = new ItemData(name, cost, priority);
}
}
}
回答by FlipMcF
Your item class:
您的物品类别:
class Item {
String name;
double cost;
int priority;
Item(String name, double cost, int priority) {
this.name = name;
this.cost = cost;
this.priority = priority;
}
}
"An Array of objects" is a misnomer in Java, because arrays have fixed-length elements. I do not think it's safe to assume all your Item objects will be the same size.
“对象数组”在 Java 中用词不当,因为数组具有固定长度的元素。我认为假设所有 Item 对象的大小都相同是不安全的。
Use a "List" - or in Java, an "ArrayList"
使用“列表”——或者在 Java 中使用“ArrayList”
ArrayList<Item> myCart = new ArrayList<Item>();
Create the item object:
创建项目对象:
Item myItem = new Item('cheese', 42.12, 1); //cheese is good
Append the item to the shopping cart:
将商品添加到购物车:
myCart.add(myItem);
http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.htmlCreating an Arraylist of Objects
http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList .html创建对象的 Arraylist
回答by Paul Renton
You should try making a User Defined Type which acts as a data structure to hold the values you desire.
您应该尝试制作一个用户定义类型,它充当数据结构来保存您想要的值。
Since java is an object oriented language, you can create a user defined type with a class. Below, I created a class called Item with three member data variables. This class is a blueprint for all Item type objects. Whenever you create a new item object, it will have its own unique copies of the member data variables.
由于 java 是面向对象的语言,因此您可以使用类创建用户定义的类型。下面,我创建了一个名为 Item 的类,其中包含三个成员数据变量。此类是所有 Item 类型对象的蓝图。每当你创建一个新的 item 对象时,它都会有它自己的成员数据变量的唯一副本。
For sake of simplicity, I did not encapsulate the member data variables, but for future programs you should declare member data variables private and provide an interface to access/modify them. Leaving them public here allows me the convenience of accessing them with the dot (.) operator.
为了简单起见,我没有封装成员数据变量,但是对于以后的程序,您应该将成员数据变量声明为私有并提供访问/修改它们的接口。在这里将它们公开让我可以方便地使用点 (.) 运算符访问它们。
See the following code for a working example
有关工作示例,请参阅以下代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Item {
public String name;
public int priority;
public double cost;
public static void main(String[] args) {
int itemAmount = 7;
List<Item> itemList = new ArrayList<Item>();
for (int i=0; i < itemAmount; i++) {
Item itemToCreate = new Item();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
itemToCreate.name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
itemToCreate.cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
itemToCreate.priority = keyboard3.nextInt();
itemList.add(itemToCreate);
} // end for
for (int i=0; i < itemList.size(); i++) {
Item tempItem = itemList.get(i);
System.out.println("Item " + tempItem.name + " has cost " + tempItem.cost + " with priority " + tempItem.priority);
}
} // end main
} // end class
You should notice I replaced your original declaration with an ArrayList data structure. This is a dynamic data structure that can grow as you insert items into it. You should take on the challenge of allowing for unlimited amount of user input and to account for an unknown quantity of Item objects in your list.
您应该注意到我用 ArrayList 数据结构替换了您的原始声明。这是一种动态数据结构,可以随着您向其中插入项目而增长。您应该接受允许无限量的用户输入并考虑列表中未知数量的 Item 对象的挑战。
Hope this helps!
希望这可以帮助!