이것은 Deitel의 저서 「How to Program, 9th Edition」에서 Exercise 6.16처럼 보입니다.
CTRL-Z charcter는 CTRL-D가 대부분의 UNIX 또는 Linux 플랫폼에서 입력을 종료하는 것처럼 실제로는 Windows 플랫폼에서 입력을 끝냅니다.
또한 프로그램 구성시 스캐너 메소드 및 System.in 바이트 스트림 (즉, 콘솔의 표준 입력)을 잘 나타내지 못하는 논리 오류가 있습니다. 게시 된 프로그램에서
, 성명 :
num = input.nextInt();
무조건 실행합니다. 어떤 종류의 입력이 수신 될 때까지 실행을 차단합니다. 입력이 정수가 아니면 예외를 throw합니다. 수신 된 입력이 정수이면 num에 정수 값이 할당되고 입력 스트림 (입력)의 정수는 입력 스트림에서 삭제됩니다. 사용자가 입력 라인을 종료 한 Enter 키를 누르기 전에 입력 한 내용에 따라 라인 끝까지 입력 라인에 잔여 물이 남아있을 수 있으며 스캐너가 스캔중인 System.in 바이트 스트림에 배치됩니다.
input.hasNext()를 while 문 테스트 조건에 넣는 것을 제외하고는 프로그램을 작성한 상태로 두는 경우 nextInt()가 처리 한 정수보다 많은 입력이 입력 스트림에있을 때까지 차단됩니다.
일부 답변은 솔루션으로 KeyBinding을 사용하는 것이 좋습니다. 작동하는 동안 거의 하드웨어 수준에서 키 누르기 이벤트를 기다리고 플랫폼 독립성에 우호적이지 않습니다. Alice 's Wonderland는 모든 종류의 이벤트 처리와 코드가 실행중인 플랫폼을 알아야하는 상황을 파악할 수있는 잠재적 인 토끼 구멍입니다. 입력 스트림의 끝이 모든 플랫폼에서 작동해야 함을 나타내려면 hasNext() 부울 false 반환을 사용하고 거의 하드웨어 이벤트 수준에서 키보드 및 키 누르기를 처리하기 위해 잠재적으로 휴대 할 수없는 gee-whiz 코드를 피할 수 있습니다.
다음 프로그램은 사용자가 (또는 연습 문제)하지 않고도 사용자가 Windows 플랫폼에서 CTRL-Z를 누르거나 UNIX/Linux 플랫폼에서 CTRL-D를 누르면 입력을 종료합니다 코드가 실행되는 플랫폼을 결정하십시오.
// Exercise 6.16: EvenOrOddTest.java
// Write a method isEven that uses the remainder operator (%)
// to determine whether an integer is even. The method should
// take an integer argument and return true if the integer is
// even and false otherwise. Incorporate this method into an
// application that inputs a sequence of integers (one at a time)
// and determines whether each is even or odd.
import java.util.Scanner;
public class EvenOrOddTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int integer;
System.out.println("Odd even integer test.");
System.out.printf("Input CTRL-Z on Windows or CTRL-D on UNIX/Linux to end input\n"
+ "or an integer between values\n"
+ "%d and %d\n"
+ "to test whether it is odd or even: ",
Integer.MIN_VALUE, Integer.MAX_VALUE);
// the input.hasNext() will block until
// some kind of input, even a CTRL-Z,
// arrives in the stream
// the body of the while loop will execute
// every time input appears for as long as the input
// is not a CTRL-Z
while (input.hasNext()) { // repeat until end of input
// prompt user
// now see if the input we did get is an integer
if (input.hasNextInt()) { // we got an integer...
integer = input.nextInt();
System.out.printf("\n%d is "
+ (EvenOrOdd.isEven(integer) ? "even.\n\n" : "odd.\n\n"), integer);
} else { // we got a non-integer one too large for int
System.out.printf("\nInput %s invalid! Try again...\n\n", input.next());
} // end if...else
// white space (i.e. spaces and tabs) are separators
// next and nextInt get only to the first separator
// so it is possible for the user to enter an integer
// followed by tabs and/or spaces followed by more
// input, integer or not up to the end of the input line
// input.nextLine() flushes everything not processed
// by the nextInt() or next() to the input line end
// won't block execution waiting for input
// if there is nothing left on the input line
input.nextLine();
// prompt for user input again
System.out.printf("Input CTRL-Z to end input\n"
+ "or an integer between values\n"
+ "%d and %d\n"
+ "to test whether it is odd or even: ",
Integer.MIN_VALUE, Integer.MAX_VALUE);
} // end while
} // end main
static boolean isEven(int integer) {
// integer modulus 2 is zero when integer is even
return ((integer % 2) == 0);
} // end isEven
} // end class EvenOrOddTest
출처
2012-07-23 22:26:59
Jim
이 키를 눌렀을 때 여러 키에 응답하려면 루프 – Joe
을 종료하려면을 입력 할 수 없다는 점을 제외하면 내가 찾고있는 것이 있습니다. 그러면 KeyBindings를 구현하는 것이 가장 좋습니다. 당신은 당신이 무엇을 요구하고 있는지를 얻기 위해 어떤 열쇠가 눌러져 있는지 들어야 만합니다. –
ChadNC