2014-03-03 125 views
0

我想完成我的实验室在我的介绍CS课程,并无法从txt文件中读取信息并使用它。阅读和使用txt文件java

下面是到目前为止我的代码:

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

public class loops { 
public static void main (String [] args) throws FileNotFoundException{ 

File myFile = new File("Snowboard_Scores.txt"); 
Scanner input = new Scanner(myFile); 

String name; 
String country; 
int snow1; 
int snow2; 
int snow3; 
double score; 
int max = 0; 

while (input.hasNext()){ 
    System.out.println(input.nextLine()); 
    max++; 
} 
System.out.println(max); 

for (int count = 0; count < max; count ++){ 

} 
} 
} 

该实验室是简单的,我比较来自不同4+滑雪三个分数。每个滑雪者都有一个名字,一个国家和3名评委。我需要平均分数,然后将其与所有滑雪板进行比较,以查看谁获得了最佳分数,然后打印出滑雪板名称和国家/地区。

我正在努力收集和存储所有数据的方式,这将是有用的。我们现在不能在我们的实验室中使用阵列,任何人对如何解决这个问题有任何想法?

Snowboard_Scores.txt:

Shaun White 
United States 
9.7 
9.8 
9.6 
Bob Saget 
Yugolsavia 
1.4 
2.1 
1.9 
Morgan Freeman 
Antartica 
10.0 
9.9 
9.8 
Diana Natalicio  
Brazil 
8.7 
8.7 
9.2 
+0

“Snowboard_Scores.txt”文件是怎么样的? – rpax

+0

对不起,应该补充一点。 连成一条线, 一线名称 二线国家 2-5分数线 6号线名称 7号线国家等 –

+0

你说你不能使用数组。你可以用什么? – rpax

回答

0

其过于简单;
在读取数据时处理数据;
读取每个滑雪板并与最佳预置值进行比较;
然后选择best作为最佳值;看到下面的代码

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

public class loops { 
public static void main (String [] args) throws FileNotFoundException{ 

    File myFile = new File("Snowboard_Scores.txt"); 
    Scanner input = new Scanner(myFile); 

    String name = ""; 
    String country = ""; 
    double score = 0.0; 

    while (input.hasNext()){ 
     String tmp_name = input.nextLine(); 
     String tmp_country = input.nextLine(); 
     double tmp = Double.parseDouble(input.nextLine())/3; 
     tmp += Double.parseDouble(input.nextLine())/3; 
     tmp += Double.parseDouble(input.nextLine())/3; 
     if(tmp > score){ 
      name = tmp_name; 
      country = tmp_county; 
      score = tmp; 
     } 
    } 
    System.out.println(name); 
    System.out.println(country); 
} 

你说得对。一行错过

+0

在初始化它之后,您从不修改分数。国家= tmp_county后; score = tmp; ? – user1399238

+0

是的那条线错过了! – vorujack

+0

这个工作,但是国家的名称不会出于任何原因显示。 –

0

只是稍作修改。

while (input.hasNext()){ 

String tmp_name = input.nextLine(); 
String tmp_country = input.nextLine(); 

double tmp_avg = Double.parseDouble(input.nextLine())/3; 
tmp_avg += Double.parseDouble(input.nextLine())/3; 
tmp_avg += Double.parseDouble(input.nextLine())/3; 

if(tmp_avg > score){ 
    score = tmp_avg; 
    name = tmp_name; 
    country = tmp_country; 
} 
}