gpt4 book ai didi

java - 在java中将文件导入到二维数组

转载 作者:行者123 更新时间:2023-11-30 04:02:43 24 4
gpt4 key购买 nike

我正在尝试从文件导入项目并将其放入 3 个不同的数组中,但出现一些错误。这是我到目前为止的代码:

package project1;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;


public class Project1 {

/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
fillArray();

}

public static void fillArray() throws IOException {
Scanner teamList = new Scanner(new File("baseball_teams.txt"));
String[] teamName = new String[35];
int[] teamRank = new int[35];
double[] teamWinPercentage = new double[35];
int i = 0;
while (teamList.hasNext()) {
teamRank[i] = teamList.nextInt();
teamName[i] = teamList.next();
teamWinPercentage[i] = teamList.nextDouble();
i++;
}
}

}

当我尝试运行该程序时收到此错误:

run:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at project1.Project1.fillArray(Project1.java:36)
at project1.Project1.main(Project1.java:23)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

这是文件的内容:

1   

Boston

0.605

2

St.Louis

0.596

3

Oakland

0.587

4

Atlanta

0.584

5

Pittsburgh

0.577

6

Detroit

0.567

7

Cleveland

0.564

8

Dodgers

0.564

9

Tampa Bay

0.559

10

Texas

0.558

11

Cincinnati

0.552

12

Washington

0.531

13

Kansas City

0.531

14

Baltimore

0.525

15

Yankees

0.525

16

Arizona

0.500

17

Angels

0.481

18

San Diego

0.469

19

Giants

0.469

20

Mets

0.457

21

Colorado

0.457

22

Milwaukee

0.457

23

Toronto

0.457

24

Philadelphia

0.451

25

Seattle

0.438

26

Minnesota

0.407

27

Cubs

0.407

28

Sox

0.389 29

Miami

0.383

30

Houston

0.315

如果有任何提示,我将不胜感激!

谢谢!

最佳答案

看来您正在对 .next*() (.next() 和 .nextInt())进行两次调用,即使在循环条件中您只检查下一个。

如果我对你的文件的假设是正确的

1 teamName1 100.0
2 teamName2 43.3
3 teamName3 43.6
4 teamName4 34.4
5 teamName5 23.2
.
.
.

如果是这样,那么也许尝试一次读取一行

int i = 0;
String[] ln = null;
while(teamList.hasNext()){
ln = String.split(teamList.nextLine()); // default is split on ' ' character
teamRank[i] = Integer.valueOf(ln[0]);
teamName[i] = ln[1];
teamWinPercentage[i] = Double.valueOf(ln[2]);
++i;
}

关于java - 在java中将文件导入到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21558092/

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