gpt4 book ai didi

java - 在方法中使用分隔符 (Java)

转载 作者:行者123 更新时间:2023-12-01 11:36:52 26 4
gpt4 key购买 nike

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

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

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

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);
}
}

这是我的输出(忽略“测试”):

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 和 amountSold 值。

去掉主方法中的 strScan 并将整行传递到 Sales 构造函数中。然后在 Sales 构造函数中执行如下操作:

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

关于java - 在方法中使用分隔符 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29880247/

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