0

我的代码片段:

...
    System.out.println("\t" + "MONTH |" + "\t" + "HIGH | " + "\t" + "LOW |" + "\t" + "AVERAGE |" + "\t" + "RANGE");
    System.out.println("\t" + "______________________________________________");

    main.averageMonthOne(hightemp, lowtemp);

    in1.close();
    out.close();                
}//end of main 


private static double averageMonthOne (int hightemp, int lowtemp)
{
    double avgM = (hightemp + lowtemp)/2;
    System.out.println(avgM);
    return avgM;
} 

我希望能够使用我收到的平均值averageMonthOne并将其分别放在 println 中的“AVERAGE”一词下。那可能吗?

预期输出:

MONTH | HIGH | LOW | AVERAGE | RANGE
_____________________________________
                      30.0
4

4 回答 4

0

相应地使用System.out.printf()和格式化!

于 2013-04-12T11:49:34.340 回答
0

很有可能只需将您的代码更改为如下所示:

...
System.out.println("\t" + "MONTH |" + "\t" + "HIGH | " + "\t" + "LOW |" + "\t" + "AVERAGE |" + "\t" + "RANGE");
System.out.println("\t" + "______________________________________________");

double myresult = main.averageMonthOne(hightemp, lowtemp);
System.out.println("\t\t\t\t" + myresult);

in1.close();
out.close();                

}//主程序结束

private static double averageMonthOne (int hightemp, int lowtemp) { double avgM = (hightemp + lowtemp)/2; System.out.println(avgM); 返回平均值;}

于 2013-04-12T11:51:43.803 回答
0

如果我在你的位置,我会创建一个字符串数组,你可以在其中放置你得到的数字。例如:

try{
    BufferedReader bufferedReader = new BufferedReader(new FileReader("fileName.txt"));
    String[] numbers = new String[5];

    for(int i=0; i<5; i++){     // here you only read 5 values from a file, line by line. If the file is formatted differently you have to read them differently.
       numbers[i] = bufferedReader.readLine();
    }
}catch(IOException io){ ... }

然后将字符串数组格式化为一个字符串行,如下所示:

String printedNumbers = "";
for(int i=0; i<numbers; i++){
    printNumbers+="\t";            // every table cell is seperated by a TAB
    if(numbers[i] == null){        // if the cell is empty
        printNumbers +=\t;         //    fill it with a TAB
    }else{ 
        printNumbers +=numbers[i]; // otherwise put the number in
    }
}

对于只有 5 个值,这可能有点多,但是您不必用空白填充“表格单元格”之间的空白。最后打印你的表做:

System.out.println("\t" + "MONTH |" + "\t" + "HIGH | " + "\t" + "LOW |" + "\t" + "AVERAGE |" + "\t" + "RANGE");
System.out.println("\t" + "______________________________________________");
System.out.println(printNumbers);
于 2013-04-12T11:54:34.213 回答
0

如果您有固定数量的字符串,则此方法可以填充或为空。准备好一堆变量,如下所示:

String avg = "", high = "", low = "", ...;

接下来,用值填充您需要的那些:

avg = averageMonthOne(hightemp, lowtemp);
high = ...;
low = ...;

最后,调用 String.format 方法将其全部收集起来:

String s = String.format("%s %s %s", avg, high, low);
System.out.println(s);

您可以将上述内容缩短为

System.out.format("%s %s %s", avg, high, low);

根据http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html,有很多用于格式化和间隔输出的选项,只需相应地更改格式方法的第一个参数.

于 2013-04-12T11:55:06.510 回答