[英]reading in and using a txt file java
我正在尝试完成CS入门课程中的实验,但是无法读取和使用txt文件中的信息。
下面是我到目前为止的代码:
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
它太简单了;
在读取数据时处理数据;
阅读每个滑雪板并与最佳前值进行比较;
然后选择“最佳”作为最佳价值; 见下面的代码
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);
}
你说的对。 错过了一行
只是稍作修改。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.