Как пользователь Scanner.hasNextInt для пуленепробиваемого кода [дубликат]

import unittest

def generator(test_class, a, b):
    def test(self):
        self.assertEqual(a, b)
    return test

def add_test_methods(test_class):
    #First element of list is variable "a", then variable "b", then name of test case that will be used as suffix.
    test_list = [[2,3, 'one'], [5,5, 'two'], [0,0, 'three']]
    for case in test_list:
        test = generator(test_class, case[0], case[1])
        setattr(test_class, "test_%s" % case[2], test)


class TestAuto(unittest.TestCase):
    def setUp(self):
        print 'Setup'
        pass

    def tearDown(self):
        print 'TearDown'
        pass

_add_test_methods(TestAuto)  # It's better to start with underscore so it is not detected as a test itself

if __name__ == '__main__':
    unittest.main(verbosity=1)

РЕЗУЛЬТАТ:

>>> 
Setup
FTearDown
Setup
TearDown
.Setup
TearDown
.
======================================================================
FAIL: test_one (__main__.TestAuto)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:/inchowar/Desktop/PyTrash/test_auto_3.py", line 5, in test
    self.assertEqual(a, b)
AssertionError: 2 != 3

----------------------------------------------------------------------
Ran 3 tests in 0.019s

FAILED (failures=1)
2
задан Bobulous 21 September 2014 в 20:38
поделиться

2 ответа

Вы были близки: это отлично работает для меня:

Scanner input = new Scanner(System.in); //construct scanner
while(!input.hasNextInt()) {
    input.next(); // next input is not an int, so consume it and move on
}
int finalInput = input.nextInt();
input.close(); //closing scanner
System.out.println("finalInput: " + finalInput);

Вызывая input.next() в вашем цикле while, вы потребляете нецелое содержимое и повторите попытку, и снова, до следующего input - int.

3
ответ дан Bobulous 25 August 2018 в 20:02
поделиться
//while (test == false) {                         // Line #1
while (!test) { /* Better notation */             // Line #2
    System.out.println("Integers only please");   // Line #3
    test = input.hasNextInt();                    // Line #4
}                                                 // Line #5

Проблема в том, что в строке # 4 выше input.hasNextInt() проверяет только если вводится целое число и не запрашивает новое целое число. Если пользователь вводит что-то другое , чем целое число, hasNextInt() возвращает false, и вы не можете запросить nextInt(), потому что тогда бросается InputMismatchException, так как Scanner все еще ожидает целое число.

Вы должны использовать next() вместо nextInt():

while (!input.hasNextInt()) {
    input.next();
    // That will 'consume' the result, but doesn't use it.
}
int result = input.nextInt();
input.close();
return result;
0
ответ дан MC Emperor 25 August 2018 в 20:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: