【问题标题】:Calorie Counter Java卡路里计数器 Java
【发布时间】:2020-06-17 21:36:02
【问题描述】:

我正在自学 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 对象的数组,因为每个这样的对象里面都有几个字符串和几个数字。

标签: java class methods


【解决方案1】:

问题说明您需要保存多种类型的数据,对象是保存这些数据的最佳方式。您首先需要创建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;
  }
}

创建此对象后,问题会指出将它们存储在一个大小为 10 的数组中,称为 salesRecord

SalesRecord[] salesRecord = new SalesRecord[10];

这个数组现在将保存SalesRecord 对象。因此具有 SalesRecord 类型,而不是典型的 int、string 或 double。

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

【讨论】:

  • 然后我需要创建一个循环来将 10 个对象存储在该数组中吗?
  • 是的,您需要创建一个循环来遍历数组的大小 (10),然后在循环中通过执行 thearrayofsize10[i] = theobjectyouradding 添加每个项目
猜你喜欢
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多