输入计数Java

时间:2013-11-18 10:01:41

标签: java exception java.util.scanner

当我开始编程时,我常常练习像这样的愚蠢练习:

所需行为 “在终端上数字一个任意选择的字符串数,然后计算它们,如果它们不是数字的话。”

字符串挖掘示例:

  

“我”,“我”,“3”,“时代”,“更好”,“比”,“是”,“4”

预期结果: 6

正确的代码:

    ArrayList<String> container = new ArrayList<>();
    Scanner input = new Scanner(System.in);
    int number = 0;

    while (number == 0) {
        System.out.println("Digit an arbitrary positive number: ");

        try {
            number = Integer.parseInt(input.next());
            if (number == 0) { throw new Exception(); }
        } catch (Exception exception) {
            System.out.println(" Exception: You didn't digit correctly! ");
        }
    }

    for (int i=0; i<number; i++ ){
        System.out.println("Enter a String : ");
        String next = input.next();
        try {
            Integer.parseInt(next);
        } catch (Exception exception) {
            container.add(next);
        }
    }
    System.out.println("You digited " + container.size() + " Strings! ");

1 个答案:

答案 0 :(得分:1)

ArrayList<String> arr = new ArrayList<String>();
while (input.hasNext()){
   String str = input.next();
   try{
       int garbage = Integer.parseInt(str); //this will fail if it's not a number
   }
   catch Exception e{
       arr.add(str);// that means we want to keep it
   }

}

现在您只想打印数组中的所有字符串,并将其大小作为您保留的字数返回。 可能不是最好的方法,但应该可以正常工作。