java - 如何用我的主类修复我的 loadData 方法
问题描述
我正在尝试从 txt 文件加载数据,它只会读取 txt 文件的一行。当我在 loadData 方法的 for 循环中指定 int I 变量时,它将打印该特定行。我不确定为什么它不只是添加和打印我的所有数据。
我尝试使用外部 for 循环来查看是否会以这种方式打印和添加数据,但没有运气
import java.io.*;
import java.util.*;
public class BingoSortTest
{
static BingoPlayer [] test;
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
test = new BingoPlayer [10];
loadData();
System.out.print(Arrays.toString(test));
}
public static void loadData() throws IOException
{
Scanner S = new Scanner(new FileInputStream("players.txt"));
double houseMoney = S.nextDouble();
S.nextLine();
int player = S.nextInt();
S.nextLine();
for(int i = 0; i < test.length; i++)
{
String line = S.nextLine();
String [] combo = line.split(",");
String first = combo [0];
String last = combo [1];
double playerMoney = Double.parseDouble(combo[2]);
BingoPlayer plays = new BingoPlayer(first, last, playerMoney);
add(plays);
}
}
public static void add(BingoPlayer d)
{
int count = 0;
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
}
这是我正在使用的 txt 文件的内容:
- 50.00
- 10
- 詹姆斯,史密斯,50.0
- 迈克尔,史密斯,50.0
- 罗伯特,史密斯,50.0
- 玛丽亚,加西亚,50.0
- 大卫,史密斯,50.0
- 玛丽亚,罗德里格斯,50.0
- 玛丽,史密斯,50.0
- 玛丽亚,埃尔南德斯,50.0
- 玛丽亚,马丁内斯,50.0
- 詹姆斯,克拉珀,50.0
解决方案
每次您在 Index 放置 BingoPlayer 时0
。
public static void add(BingoPlayer d)
{
int count = 0; // <-------------------- Here
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
您必须在定义 BingoPlayer 数组的位置定义静态计数器变量。
定义计数变量静态
static BingoPlayer [] test;
static int count = 0;
并像这样更改添加函数定义。
public static void add(BingoPlayer d)
{
if (count< test.length) {
test[count] = d;
count++;
}
else
System.out.println("No room");
}
推荐阅读
- python - 如何将缓存文件图像添加到 Django HttpResponse
- json - 为什么 JsonResponse 不会自动序列化我的 Django 模型?
- typescript - tsc cli - 检查 src 文件是否比目标文件新
- angular - Angular 7 自定义组件 registerOnChange 不是一个函数
- html - 我无法将我的表格与 html/css 中的嵌入视频对齐
- regex - 最多一个中缀 00 和一个中缀 11 的正则表达式
- javascript - 如何在 laravel 视图中添加外部 Javascript
- android - Flutter android_alarm_manager 插件不会定期运行
- javascript - 将参数传递给Vue.js中多选的@select - vue-multiselect
- sql - SQL:计算每个国家的红黄牌数量