这是一个简单的程序。我被分配将对象存储在一个数组中。但由于我是初学者,所以我不知道如何在阵列中存储对象。有人可以帮我解决这个问题吗?
import java.util.Scanner;
public class MainExample {
public static void main(String[] args) {
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
if ("yes".equals(input))
repeat = true;
else
repeat = false;
}
}
}
答案 0 :(得分:0)
虽然不是很优雅,但这个玩具程序的快速解决方案是制作一个“房间”类,其中包含各种属性,如“长度”,“宽度”,“price_per_sqft”等。然后你可以设置每个属性的特定属性。房间对象并将“房间”对象存储在“房间”数组中。
答案 1 :(得分:0)
你想在数组中存储什么?不同的final_price
值?
无论如何,因为您不知道循环运行的次数,您可能需要一个ArrayList。您可以通过添加ArrayList <Double> prices = new ArrayList <Double> ();
然后,在循环的末尾添加一行,将正确的变量存储到ArrayList中。例如:prices.add(final_price);
如果final_price
不是您要存储的内容,则只需将其替换为您要存储的变量。
另外,请不要忘记,如果您使用ArrayList,则需要在代码顶部使用正确的import语句:import java.util.ArrayList;
答案 2 :(得分:0)
你需要创建一个类来保存这样的属性。创建一个构造函数来初始化这些值。
public class Room{
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
}
然后在main方法/驱动程序类中创建一个具有此类类型的数组并存储相关对象。
Room arr=new Room[100];
int count=0;
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
arr[count]=new Room(length,width,price1,price2,price3,price4);//call to the constructor
if ("yes".equals(input))
repeat = true;
count++;
else
repeat = false;
}
}