我自学Java,并遇到了这个问题。

它需要采用多种方法,还需要将用户数据放入数组中。

我很困惑,因为数组不仅不必是浮点数,整数或双精度型或字符串,也不能既是字符串又是双精度型。但是用户正在输入多种数据。我在下面添加问题,以及到目前为止编写的代码。

enter image description here
我已附上问题的图片

import java.util.Scanner;

public class salesRecord {

    String Itemname;
    int Quantity;
    float unitPrice;
    static float total;
    String status; //for credit or debit

    void data() {

        Scanner input=new Scanner(System.in);
        System.out.println("Enter your Item name: ");
        Itemname=input.next();
        System.out.println("Enter your Quantity: ");
        Quantity=input.nextInt();
        System.out.println("Enter your Unit Price: ");
        unitPrice=input.nextFloat();
        System.out.println("What is your Status: ");
        status=input.next();

        total=Quantity*unitPrice;

    }

    void ShowData() {


        System.out.println("Item name is: "+Itemname);
        System.out.println("Quantity is: "+Quantity);
        System.out.println("Price per unit is: "+unitPrice);
        System.out.println("Credit or Debit: "+status);
        System.out.println("Total Price is: "+ total);
    }



    public static void main(String[] args) {

        salesRecord cus1=new salesRecord();
        Scanner inputcashier=new Scanner(System.in);
        System.out.println("How many items do you have: ");
        int items=inputcashier.nextInt();

        for (int i = 0; i < items; i++) {

            cus1.data();
            cus1.ShowData();
            total=total+total;
        }

        System.out.println("Your grand total is: "+total);

    }


}

最佳答案

问题表明您需要保存多种类型的数据,对象是保存此数据的最佳方法。您首先需要创建SalesRecord

class SalesRecord{
  String itemName;
  double unitPrice;
  double total;
  String status;

  // constructor
  SalesRecord(String _itemName,double _unitPrice,double _total,String _status){
    this.itemName = _itemName;
    this.unitPrice = _unitPrice;
    this.total = _total;
    this.status = _status;
  }
}


创建该对象后,问题便会指出将它们存储在名为salesRecord的数组大小10中

SalesRecord[] salesRecord = new SalesRecord[10];


现在,该数组将保存SalesRecord对象。因此,其类型为SalesRecord,而不是典型的int,string或double。

Here's a good intro to creating and storing objects.

08-16 18:51