1

说这是我的代码:

String name = in1.next();
int highNumber = in1.nextInt();
int lowNumber = in1.nextInt();

System.out.println(name +" " + highNumber +" " + lowNumber);

name如果不是 12 ,有没有办法可以在前面添加一个数字?或者有没有办法创建一个ArrayList做同样的事情?

我需要从一个文件中获取 12 行,每行都带有name, highNumber,并且lowNumber 我希望能够单独操作每个等式,也可以完全操作。

文件:

Edward 33 22
Billy  22 14
Fred   44 43
Jim    12  1
Andy   3   2
...

预期输出:

Name             High             Low             Average            Range
--------------------------------------------------------------------------
Billy             22                14             18                  8
...

Total Averages
Total Highs
Total Lows

替代做这样的事情:

String name2 = in1.next();
int highNumber2 = in1.nextInt();
int lowNumber2 = in1.nextInt();
String name3 = in1.next();
int highNumber3 = in1.nextInt();
int lowNumber3 = in1.nextInt();
String name4 = in1.next();
int highNumber4 = in1.nextInt();
int lowNumber4 = in1.nextInt();
...
String name12 = in1.next();
int highNumber12 = in1.nextInt();
int lowNumber12 = in1.nextInt();

我被限制使用Scannerand PrintWriter。:(

4

3 回答 3

2

您可以将每一行的数据存储在这样的对象中

public class Record {
    private String name;
    private Integer high;
    private Integer low;

    public Record(String name, Integer high, Integer, low) {
        this.name = name;
        this.high = high;
        this.low = low;
    }

    public Record(String line) {
        String[] parts = line.split(" ");
        name = parts[0].trim();
        high = new Integer(parts[1].trim());
        low = new Integer(parts[2].trim());
    }

    public String getName() {
        return name;
    }

    public Integer getHigh() {
        return high;
    }

    public Integer getLow() {
        return low;
    }

    public Integer getAvg() {
        return (high + low) / 2;
    }

    public Integer getRange() {
        return (high - low);
    }

    public String toString() {
        return name + '\t' + high + '\t' + low  +'\t' + getAvg() + '\t' + getRange();
    }
}

然后将从文件中读取的行填充到新的 Record 对象中,将它们附加到列表中,最后遍历列表以打印表

List<Record> records = new ArrayList<Record>();
String name;
Integer high;
Integer low;

for(int i = 0; i < 12; i++) {
    name = in1.next();
    high = in1.nextInt();
    low = in1.nextInt();

    records.add(new Record(name, high, low));
}

for(Record record : records) {
    System.out.println(record);
}
于 2013-04-12T08:34:01.773 回答
1
Scanner in=new Scanner(new File(""));
System.out.println("Id\tName\tHigh\tLow\tAvg\tRange");
int id=1;
while(input.hasNext())
{
String name=input.next();
int high=input.nextInt();
int low=input.nextInt();
System.out.println(id+"\t"+name+"\t"+high+"\t"+low+"\t"+((high+low)/2)+"\t"+(high-low));
id++;
}

你期待这个吗???给更多细节..

于 2013-04-12T09:01:11.590 回答
0

可能是一条阅读线?

BufferedReader File = new BufferedReader(new FileReader(FileOpen));   
     String str;
     str = File.readLine( );

当第一行读取然后再做 readLine() with a boule for(){}

于 2013-04-12T08:27:19.820 回答