while循环用于多个输入

时间:2017-11-07 04:39:15

标签: java

我知道这可能是一个简单的答案,但由于某种原因,它超出了我。我的班级现在在BlueJ工作,我们正在用正方形创建一个图表上的点,现在我需要进行以下提示循环,直到某个条件(x = -1)继续输入与用户认为合适。

public void plotPoints(Scanner keyboard)
{

            System.out.print("Enter an x and y coordinate: ");


            //Read x from user
            int x = keyboard.nextInt(); 

            //Read y from user
            int y = keyboard.nextInt();

            //Plot the point
            new Circle(x,y);
}

建议我们使用while循环。

2 个答案:

答案 0 :(得分:0)

此代码可以完成工作。

public class PlotPoints {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        PlotPoints pp = new PlotPoints();
        pp.plotPoints(sc);
    }
    public void plotPoints(Scanner keyboard)
    {
        int x=1;
        while (x != -1) {

            System.out.print("Enter an x and y coordinate: ");


            //Read x from user
            x = keyboard.nextInt();

            //Read y from user
            int y = keyboard.nextInt();

            //Plot the point
            new Circle(x, y);
        }
    }
}

答案 1 :(得分:0)

您可以使用无限while或for循环使用中断条件,如下所示:

public List<Circle> plotPoints(Scanner keyboard){

    List<Circle> arrList = new ArrayList<>();

    while(true){ // for(;;) {

        System.out.println("Enter an x and y coordinate: ");

        System.out.println("Enter value for x: (x=-1 to exit)");
        //Read x from user
        int x = keyboard.nextInt(); 
        System.out.println("x =" + x);

        if(x == -1){
           System.out.println("Good bye!");
           break;
        }

        //Read y from user
        System.out.println("Enter value for y: ");
        int y = keyboard.nextInt();
        System.out.println("y = " + y);
        System.out.println("Plotting point (" + x + "," +  y + ")");

        //Plot the point            
        arrList.add(new Circle(x,y));
     }

     return arrList;

}

上面的代码给出了获取用户希望输入的参数的逻辑。该方法假设返回绘制点的集合,因此数组列表arrList用于收集所有绘制点。起初我以为你试图绘制圆圈,但这是不可能的,因为你没有得到半径的值。