在方法中使用定界符 (Java)

Using a delimiter in a method (Java)

我必须从文本文件的一行中读取输入:

1165,24
1305,27
1345,12
1360,10
1388,15
1388,20
1495,32
1680,36

并将其发送到一个方法,该方法将构建一个销售对象,行中的第一个数字是产品代码,第二个数字是销售数量。现在我的代码正在获取第一个数字,创建一个 Sales 对象并将其设置为两者,然后获取下一个数字,创建一个 Sales 对象并将其设置为 Product code 和 Quantity Sold。

import java.util.Scanner;
import java.io.*;

public class Proj2 {
    public static void main(String[] arg) throws IOException {
        String str;
        Scanner fileScan, strScan;

        fileScan = new Scanner (new File("SoldSorted.txt"));
        System.out.println("Test");
        while (fileScan.hasNext())
        {
            str = fileScan.nextLine ();
            //System.out.println ();

            strScan = new Scanner (str);
            strScan.useDelimiter(",");

            while (strScan.hasNext()){
                //System.out.println ("Product Code: " + strScan.next());
                //System.out.println ("Quantity: " + strScan.next());
                Sales x = new Sales(strScan.next());
                x.printSales();
            }

        }
    }
}



public class Sales {
    int productCode, quantitySold;

    public Sales(String productSold) {
        System.out.println("Test");
        productCode = Integer.parseInt(productSold);
        quantitySold = Integer.parseInt(productSold);
    }

    public void setProduct(int product) {
        productCode = product;
    }

    public void setSold(int sold) {
        quantitySold = sold;
    }

    public int getProduct() {
        return productCode;
    }

    public int getSold() {
        return quantitySold;
    }

    public void printSales(){
        System.out.println("Product Code: " + productCode);
        System.out.println("Quantity Sold: " + quantitySold);
    }
}

这是我的输出(忽略"Tests"):

Test
Test
Product Code: 1165
Quantity Sold: 1165
Test
Product Code: 24
Quantity Sold: 24
Test
Product Code: 1305
Quantity Sold: 1305
Test
Product Code: 27
Quantity Sold: 27
Test
Product Code: 1345
Quantity Sold: 1345
Test
Product Code: 12
Quantity Sold: 12
Test
Product Code: 1360
Quantity Sold: 1360
Test
Product Code: 10
Quantity Sold: 10
Test
Product Code: 1388
Quantity Sold: 1388
Test
Product Code: 15
Quantity Sold: 15
Test
Product Code: 1388
Quantity Sold: 1388
Test
Product Code: 20
Quantity Sold: 20
Test
Product Code: 1495
Quantity Sold: 1495
Test
Product Code: 32
Quantity Sold: 32
Test
Product Code: 1680
Quantity Sold: 1680
Test
Product Code: 36
Quantity Sold: 36

我的问题是如何让数字关联到正确的变量?

您将每一行拆分为两个值,然后为每个值创建两个新的 Sales 对象,并且每个新的 Sales 对象都为 productCode 和 quantitySold 解析相同的值。

去掉 main 方法中的 strScan 并将整行传递给 Sales 构造函数。然后在您的销售构造函数中,执行如下操作:

String[] productAndQuantity = productSold.split(",");
if (productAndQuantity.length == 2) {
    productCode = Integer.parseInt(productAndQuantity[0]);
    quantitySold = Integer.parseInt(productAndQuantity[1]);
} else {
    // TODO handle missing values
}