Java 多输入的While循环
我知道这可能是一个简单的问题,答案也很简单,但出于某种原因,我无法理解。我的类现在正在BlueJ中工作,我们正在用正方形创建的图形上绘制点,现在我需要执行以下提示循环,直到某个条件(x=-1)继续执行用户认为合适的输入Java 多输入的While循环,java,Java,我知道这可能是一个简单的问题,答案也很简单,但出于某种原因,我无法理解。我的类现在正在BlueJ中工作,我们正在用正方形创建的图形上绘制点,现在我需要执行以下提示循环,直到某个条件(x=-1)继续执行用户认为合适的输入 public void plotPoints(Scanner keyboard) { System.out.print("Enter an x and y coordinate: "); //Read x from user
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循环。此代码完成此工作
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);
}
}
}
您可以使用带有中断条件的无限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;
}
公共列表打印点(扫描仪键盘){
List arrList=new ArrayList();
while(true){//for(;;){
System.out.println(“输入x和y坐标:”);
System.out.println(“输入x的值:(x=-1以退出)”;
//从用户处读取x
int x=keyboard.nextInt();
System.out.println(“x=”+x);
如果(x==-1){
System.out.println(“再见!”);
打破
}
//从用户处读取y
System.out.println(“输入y的值:”);
int y=keyboard.nextInt();
System.out.println(“y=“+y”);
System.out.println(“打印点(“+x+”,“+y+”));
//描绘要点
添加(新圆圈(x,y));
}
返回列表;
}
上面的代码给出了获取用户希望输入的尽可能多的参数的逻辑。该方法假设返回一组打印点,因此数组列表
arrList
用于收集所有打印点。起初我以为您试图绘制圆,但这是不可能的,因为您没有获得r半径。这不是javascript。哦,好吧,只是普通java?是的,这是java,不是javascript。如果你必须获得尽可能多的输入,那么用户必须迭代输入参数。因此你应该使用循环;for
或while
。请参阅以了解。我建议在这种情况下使用while,因为你想执行循环至少一次。非常有趣,我在发布之前尝试了一些非常类似的方法,但没有正确运行。我不确定我做错了什么,我不再有代码。但是我很感谢你提醒我这些代码是有效的。