gpt4 book ai didi

Java 将多个输入值存储到单个数组元素

转载 作者:行者123 更新时间:2023-12-01 07:57:37 24 4
gpt4 key购买 nike

我想将所有输入值传递给数组中的一个元素。我尝试过使用数组,但不太了解它们如何处理多个输入值。 p>

我读过 Oracle 和这里​​的内容,但没有什么真正突出的,或者他们诉诸数组列表。

有没有办法封装这些值,然后将它们存储到数组中?

非常感谢任何帮助。

import java.util.Scanner;

class Mobile
{
private String name;
private int number;
private int quantity;
private double cost;

public Mobile(String name, int number, int quantity, double cost)
{
this.name = name;
this.number = number;
this.quantity = quantity;
this.cost = cost;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getNumber()
{
return number;
}
public void setNumber(int number)
{
this.number = number;
}
public int getQuantity()
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public double getCost()
{
return cost;
}
public void setCost(double cost)
{
this.cost = cost;
}
public double getValue()
{
return cost*quantity;
}
}

public class MobilePhone
{
public static void main (String args[])
{
String itemName;
int itemNum;
int itemQuan;
double unitCost;

for(int i=0;i<5;i++)
{
Scanner input = new Scanner(System.in);

System.out.print("Enter Item Name: ");
itemName = input.nextLine();

System.out.print("Enter Item Number: ");
itemNum = input.nextInt();

System.out.print("Enter Quantity of Item: ");
itemQuan = input.nextInt();

System.out.print("Enter Price of Single Unit: ");
unitCost = input.nextDouble();

Mobile m = new Mobile(itemName, itemNum, itemQuan, unitCost);
}
}
}

最佳答案

我的理解是,您希望将手机放入长度为 5 的数组中,每个输入的手机对应一个数组。因此,您可以声明一个数组 Mobile mobileValues[] = new Mobile[5];,并在收集数据后将每个值放入数组中 mobileValues[i] = new Mobile(itemName, itemNum、itemQuan、unitCost);

public static void main (String args[])
{
String itemName;
int itemNum;
int itemQuan;
double unitCost;
Mobile mobileValues[] = new Mobile[5];

for(int i=0;i<5;i++)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Item Name: ");
itemName = input.nextLine();
System.out.print("Enter Item Number: ");
itemNum = input.nextInt();
System.out.print("Enter Quantity of Item: ");
itemQuan = input.nextInt();

System.out.print("Enter Price of Single Unit: ");
unitCost = input.nextDouble();

mobileValues[i] = new Mobile(itemName, itemNum, itemQuan, unitCost);
}
}

关于Java 将多个输入值存储到单个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28055706/

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