Java 在系统输出中对齐双(可变)列
基本上,我试图输出如下值:Java 在系统输出中对齐双(可变)列,java,output,Java,Output,基本上,我试图输出如下值: 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.parseDo
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.
您可能需要添加额外的“\t”(制表符)字符以使其对齐。我在“\t”前面留有空格的原因是为了保证标签和值之间至少有一个空格。(如果光标已经位于某个位置,则制表符可能无效)我将使用
StringBuffer
来计算前缀长度:
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));
}
计算所有字符串的最大长度。如果他们在阵列中,这将更容易。然后在打印时使用PAD。看看如何在Java中使用PAD,这似乎是最简单、最有效的方法。谢谢
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