如何自动增加字符串/整数以提高效率?

时间:2013-04-12 08:08:43

标签: java arraylist

说这是我的代码:

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

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

如果它不是12,我有没有办法在name前加上一个数字? 或者有没有办法创建ArrayList来做同样的事情?

我需要从文件中获取12行,每行包含namehighNumberlowNumber 我希望能够分别操作每个方程式,也可以完全操作。

文件:

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();

我被限制使用ScannerPrintWriter。 :(

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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++;
}

你期待这个???提供更多细节..

答案 2 :(得分:0)

可能是一条读线?

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

当第一行读取时,再使用boucle for(){}

再次执行readLine()