0

我一直在这里搜索,似乎找不到什么可以帮助我修复我的代码。

当用户输入 2 和 2 时,我试图输出 pring (2.0, 2.0)。我注释掉了需要帮助的代码。我想使用 printf 来获得我的结果。除了错误,我什么也得不到。
我的假设是问题出在我必须在文本之间打印 (2.0, 2.0) 的位置,但是我无法解决我的错误。

import java.util.Scanner;

public class prtest {

    // checks to see if radom point entered by user is within rectangle
    // rectangle is centered at (0,0) and has a width of 10 and height of 5

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter a point with two coordinates: ");
        int x = input.nextInt();
        int y = input.nextInt();

        double hDistance = Math.pow(x * x, 0.5f);// heigth distance

        double vDistance = Math.pow(y * y, 0.5f);// vertical distance

        if ((hDistance <= 10 / 2) && (vDistance <= 5.0 / 2))

            System.out
                    .print("Point (" + x + ", " + y + ") is in the rectangle");

        // System.out.printf("Point ( %1f", ", " + y + ") is in the rectangle");

        else
            System.out.print("Point (" + x + ", " + y
                    + ") is not in the rectangle");

        // System.out.printf("Point ( %1f", ", " + y +
        // ") is not in the rectangle");

    }// end main
}// end prtest
4

2 回答 2

1

System.out.printf以错误的方式使用该方法。您的方法应该像这样使用它:

System.out.printf("Point (%.1f, %.1f) is in the rectangle", x*1.0, y*1.0);
//...
System.out.printf("Point (%.1f, %.1f) is not in the rectangle", x*1.0, y*1.0);

或者更好的是,您可以将点作为整数处理

System.out.printf("Point (%d, %d) is in the rectangle", x, y);
//...
System.out.printf("Point (%d, %d) is not in the rectangle", x, y);

了解 og 用法的更多信息System.out.printf格式化字符串语法

于 2013-02-02T22:11:57.333 回答
0

以下似乎对我有用。

System.out.printf("Point , ('%1.1f', '%1.1f') 在矩形内", (double) x, (double) y);

于 2013-02-02T22:21:18.853 回答