使用集合处理用户错误

时间:2014-02-11 19:51:05

标签: java input error-handling set robustness

我已经完成了这段代码,除了我需要用户在Universe边界内输入数字之外,它几乎正确运行。我确保用户不能输入除整数之外的任何内容。但我不确定如何确保数字为1-10(宇宙集)。有人可以给我一些指导吗?

这是我的代码:

import java.util.*;
public class sets {
  public static void main (String[] args) {
  Scanner in = new Scanner(System.in);

  //declare the universe in a set
  Set universe = new HashSet();
  for (int i = 1; i <= 10; i++) {
    universe.add(i);
  }

  //Ask the user how many elements and declare set A
  System.out.print("How many elements in Set A? ");
  int elementsA = in.nextInt();
  Set A = new HashSet();

 for (int j = 1; j <= elementsA; j++) {
   System.out.print("Enter a number 1-10: ");
   while (!in.hasNextInt()) {
     in.next();
     System.out.println("Input must be a number.");
     System.out.print("Enter a number 1-10: "); 
   }
   int numA = in.nextInt();
   A.add(numA);
 }

 //Ask the user how many elements and declare set B
 System.out.print("How many elements in Set B? ");
 int elementsB = in.nextInt();
 Set B = new HashSet();

 for (int k = 1; k <= elementsB; k++) {
  System.out.print("Enter a number 1-10: ");
  while (!in.hasNextInt()) {
   in.next();
   System.out.println("Input must be a number.");
   System.out.print("Enter a number 1-10: "); 
  }
  int numB = in.nextInt();
  B.add(numB);
}

//get the union of the sets
Set union = new HashSet(A);
union.addAll(B);
System.out.println("The union of A and B: "+union);

//get the intersection of the sets
Set intersect = new HashSet(A);
intersect.retainAll(B);
System.out.println("The intersection of A and B: "+intersect);
}
}

1 个答案:

答案 0 :(得分:0)

这样的东西
while (!in.hasNextInt()) {
  in.next();
  System.out.println("Input must be a number.");
}

int numA = in.nextInt();

while (numA < 0 || numA > 10) {
  System.out.print("Enter a number 1-10: "); 
  numA = in.nextInt(); 
}

A.add(numA);

编辑:考虑到上述情况,我会更加强化解决方案,如下所示

while (true) {
    if (!in.hasNextInt()) {
        System.out.println("Input must be a number.");
        in.next();
    } else {
        int num = in.nextInt();

        if (num < 0 || num > 10) {
            System.out.println("Input must be between 1 and 10 (inclusive).");
        } else {
            // add num to collection
            break;
        }
    }
}