import javax.swing.JOptionPane;
public class HW {
public static void main(String[] args)
{
String x1 = JOptionPane.showInputDialog(null, "X: ");
String y1 = JOptionPane.showInputDialog(null, "Y: ");
double x = Double.parseDouble(x1);
double y = Double.parseDouble(y1);
System.out.println("Sum: " + (x+y));
System.out.println("Difference: " + (x-y));
System.out.println("Product: " + (x*y));
System.out.println("Average: " + (x+y)/2);
System.out.println("Distance: " + Math.abs(x-y));
System.out.println("Maximum Value: " + Math.max(x,y));
System.out.println("Minimum Value: " + Math.min(x,y));
}
}
基本上,我正在尝试将值输出为:
Sum: 5
Difference: 10
Product: 7
etc.
我已经找到了如何使用字符串执行此操作,但我不确定如何使用变量来完成此操作。
答案 0 :(得分:1)
最简单的解决方案,硬编码排列文本所需的标签数量。对于像这样的小型程序来说很好。
public static void main(String[] args)
{
String x1 = JOptionPane.showInputDialog(null, "X: ");
String y1 = JOptionPane.showInputDialog(null, "Y: ");
double x = Double.parseDouble(x1);
double y = Double.parseDouble(y1);
System.out.println("Sum: \t\t" + (x+y));
System.out.println("Difference: \t" + (x-y));
System.out.println("Product: \t" + (x*y));
System.out.println("Average: \t" + (x+y)/2);
System.out.println("Distance: \t" + Math.abs(x-y));
System.out.println("Maximum Value: \t" + Math.max(x,y));
System.out.println("Minimum Value: \t" + Math.min(x,y));
}
您可能需要添加其他'\ t'(标签)字符才能使其排成一行。我在'\ t'之前留空的原因是为了保证标签和值之间至少有1个空格。 (如果光标已经在某个位置,则Tab无效)
答案 1 :(得分:0)
我会用StringBuffer
来计算前缀长度:
public class HelloWorld {
public static void main(String args[]){
String x = JOptionPane.showInputDialog(null, "X: ");
String y = JOptionPane.showInputDialog(null, "Y: ");
System.out.println(print("Sum:", (x+y)+""));
System.out.println(print("Difference:", (x-y)+""));
System.out.println(print("Product:", (x*y)+""));
System.out.println(print("Average:", (x+y)/2+""));
System.out.println(print("Distance:", Math.abs(x-y)+""));
System.out.println(print("Maximum Value:", Math.max(x,y)+""));
System.out.println(print("Minimum Value:", Math.min(x,y)+""));
}
private static String print(String prefix, String value){
StringBuilder buff = new StringBuilder();
int length = prefix.length();
int mLength = 15; // this is your gap between title and value
buff.append(prefix);
while(length <= mLength){
buff.append(" ");
length++;
}
buff.append(value);
return buff.toString();
}
}
输出:
Sum: 7.0
Difference: -3.0
Product: 10.0
Average: 3.5
Distance: 3.0
Maximum Value: 5.0
Minimum Value: 2.0