2
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.

我已经找到了如何使用字符串来做到这一点,但我不确定如何使用变量来实现这一点。

4

2 回答 2

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 无效)

于 2013-09-30T20:49:50.177 回答
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
于 2013-09-30T20:56:01.530 回答