我正在尝试制作一些代码,询问用户他们想要完成哪些功能(例如在图表上查找哪个象限,等等)。但我也希望代码要求用户重新输入一个数字,如果它不在1和6之间(包括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));
只有当用户输入有效数字而不是输入无效数字时,才能进行循环循环。做这种事情的时候,我倾向于使用套装,所以布尔逻辑很容易,即使在没有睡眠2天和10盆冷咖啡后:)
Set<Integer> validInputs = new Set();
validInputs.add(1);
validInputs.add(2);
do {
// your stuff here
} while (!validInputs.contains(inputMethod));
如果您远离基于控制台的用户交互,拥有一组有效值将有助于swing和JavaFX。
将whichMethod = scan.nextInt()添加为默认的最后一行。如果用户输入的号码不正确,这将允许用户输入有效号码。