Issue
When I terminate the Scanner function, for some reason it doesn't print the last message in my code. I tried searching and found no solution.
This is my code:
import java.util.Scanner;
public class E2{
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
Scanner data = new Scanner(System.in);
// Your code here
int counter = 0;
while(data.hasNext()){
if(data.nextInt() == n){
counter++;
}
}
System.out.println("Number " + n + " occurred " + counter + " times.");
}
}
When I terminate the program, sometimes it prints the last message; most of the time it ignores the last message entirely.
Solution
Define 'terminate'. If you end standard input, data.hasNext() returns false, and the last message prints as expected. On some systems, this is CTRL+Z (mostly, windows). On others, it's CTRL+D. You can usually also tell the app to close, which often both ends the app and ends the input, at which point its a race. This is usually done (depends on OS) with CTRL+C.
If that's what you're doing: Don't. It's not a sensible thing to tell an app to close and then ask: Okay, but, I want to do something else. If you insist on doing this, java makes that very difficult, because this inter-process communication stuff is generally called 'signals', it's different between OSes, and java takes the view that things that cannot easily and uniformly be done on all platforms java runs on, are best not done at all, and thus rarely exposes functionality in its API that is OS-specific. Which includes signals: Trying to 'catch' the "close the app" signal is tricky.
Often apps just do this signalling inside the app itself. For example, by defining some sentinel value that means 'actually, exit'. Here is an example:
import java.util.Scanner;
public class E2 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
Scanner data = new Scanner(System.in);
// Your code here
int counter = 0;
while(data.hasNext()){
String next = data.next();
if (next.equalsIgnoreCase("done")) break;
int v = Integer.parseInt(next);
if(v == n) counter++;
}
System.out.println("Number " + n + " occurred " + counter + " times.");
}
}
This code is similar, but results in the app shutting down (and printing your message) if you enter 'done' instead of a number.
Or even simpler you could state that '0' results in app termination, then you can keep .nextInt().
Answered By - rzwitserloot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.