我的代码片段:
...
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
答案 0 :(得分:0)
使用System.out.printf()
并相应地格式化!
答案 1 :(得分: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); 返回avgM; }
答案 2 :(得分: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行,如下所示:
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个值,但你不应该用whitspace填补你的“表格单元格”之间的空白。最后要打印你的表格:
System.out.println("\t" + "MONTH |" + "\t" + "HIGH | " + "\t" + "LOW |" + "\t" + "AVERAGE |" + "\t" + "RANGE");
System.out.println("\t" + "______________________________________________");
System.out.println(printNumbers);
答案 3 :(得分: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,有很多格式化和间隔输出的选项,只需相应地更改格式方法的第一个参数。