我正在尝试编写一些代码,询问用户他们想要完成什么功能(例如,找到一个点在图形上的哪个象限,等等)。但是我还希望代码要求用户重新输入一个数字(如果该数字不在1到6之间)。我试图通过创建一个do-while循环来做到这一点,但是由于某种原因,它甚至不会循环。使其更短/更清洁的任何技巧都受到赞赏。
以下是我遇到的问题:
int whichMethod;
do{
whichMethod = scan.nextInt();
switch(whichMethod){
case 1:
System.out.println("Enter x and y values:");
x = scan.nextDouble();
y = scan.nextDouble();
Point p = new Point(x, y);
System.out.println("Quadrant:"+ p.quadrant());
break;
case 2:
System.out.println("Enter x and y values:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case2p = new Point(x, y);
case2p.flip();
System.out.println("Flipped Coordinates" + case2p);
break;
case 3:
System.out.println("Enter x and y values:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case3p = new Point(x, y);
System.out.println("Enter x and y values for the 2nd Point: ");
x = scan.nextDouble();
y = scan.nextDouble();
Point case3p2 = new Point(x, y);
System.out.println("Manhattan Distance:"+
case3p.manhattanDistance(case3p2));
break;
case 4:
System.out.println("Enter x and y values:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case4p = new Point(x, y);
System.out.println("Enter x and y values for the 2nd Point: ");
x = scan.nextDouble();
y = scan.nextDouble();
Point case4p2 = new Point(x, y);
System.out.println("Are they Vertical?: " + case4p.isVertical(case4p2));
break;
case 5:
System.out.println("Enter x and y values:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case5p = new Point(x, y);
System.out.println("Enter x and y values for the 2nd Point:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case5p2 = new Point(x, y);
System.out.println("Slope is: " + case5p.slope(case5p2));
break;
case 6:
System.out.println("Enter x and y values:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case6p = new Point(x, y);
System.out.println("Enter x and y values for the 2nd Point:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case6p2 = new Point(x, y);
System.out.println("Enter x and y values for the 3rd Point:");
x = scan.nextDouble();
y = scan.nextDouble();
Point case6p3 = new Point(x, y);
System.out.println("Are they Collinear?: "+ case6p.isCollinear(case6p2, case6p3));
break;
default:
System.out.println("This isn't one of the methods available.");
System.out.println("Please enter a number between 1 and 6");
}
} while((whichMethod >= 1) && (whichMethod <= 6));
答案 0 :(得分:0)
仅当用户输入有效号码而不是用户输入无效号码时,您才可以循环循环。 在做这种事情时,我倾向于使用集合,这样布尔逻辑很容易,即使在两天不睡觉和十壶冷咖啡的情况下:)
Set<Integer> validInputs = new Set();
validInputs.add(1);
validInputs.add(2);
do {
// your stuff here
} while (!validInputs.contains(inputMethod));
如果您远离基于控制台的用户交互,那么拥有一组有效值将有助于swing和JavaFX。
答案 1 :(得分:0)
在默认值的最后一行添加whichMethod = scan.nextInt()。如果用户输入了错误的号码,这将允许用户输入有效的号码。