How to terminate Scanner when input is complete? - java

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
}
} finally {
scan.close();
}
}
Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:
if (scan.nextLine() == null) System.exit(0);
and
if (scan.nextLine() == "") System.exit(0);
They did not work.... The program continues and messes with the original intention,

The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.
There are two ways that the user could do this:
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.
Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.
(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)
The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods. (See How do I compare strings in Java?)
Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").

String comparison is done using .equals() and not ==.
So, try scan.nextLine().equals("").

You will have to look for specific pattern which indicates end of your input say for example "##"
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
if (line.equals("##")) {
System.exit(0);
scan.close();
}
}
} finally {
if (scan != null)
scan.close();
}

In this case, I recommend you to use do, while loop instead of while.
Scanner sc = new Scanner(System.in);
String input = "";
do{
input = sc.nextLine();
System.out.println(input);
} while(!input.equals("exit"));
sc.close();
In order to exit program, you simply need to assign a string header e.g. exit. If input is equals to exit then program is going to exit. Furthermore, users can press control + c to exit program.

You can check the next line of input from console, and checks for your terminate entry(if any).
Suppose your terminate entry is "quit" then you should try this code :-
Scanner scanner = new Scanner(System.in);
try {
while (scanner.hasNextLine()){
// do your task here
if (scanner.nextLine().equals("quit")) {
scanner.close();
}
}
}catch(Exception e){
System.out.println("Error ::"+e.getMessage());
e.printStackTrace();
}finally {
if (scanner!= null)
scanner.close();
}
Try this code.Your terminate line should be entered by you, when you want to close/terminate the scanner.

With this approach, you have to explicitly create an exit command or an exit condition. For instance:
String str = "";
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) {
//Handle string
}
Additionally, you must handle string equals cases with .equals() not ==. == compares the addresses of two strings, which, unless they're actually the same object, will never be true.

Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int is a double produces a double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args){
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("Hi temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}

You can check if the user entered an empty by checking if the length is 0, additionally you can close the scanner implicitly by using it in a try-with-resources statement:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter input:");
String line = "";
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNextLine()
&& (line = scan.nextLine().toLowerCase()).length() != 0) {
System.out.println(line);
}
}
System.out.println("Goodbye!");
}
}
Example Usage:
Enter input:
A
a
B
b
C
c
Goodbye!

Related

no output after infinite while loop with hasNext() java [duplicate]

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
}
} finally {
scan.close();
}
}
Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:
if (scan.nextLine() == null) System.exit(0);
and
if (scan.nextLine() == "") System.exit(0);
They did not work.... The program continues and messes with the original intention,
The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.
There are two ways that the user could do this:
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.
Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.
(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)
The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods. (See How do I compare strings in Java?)
Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").
String comparison is done using .equals() and not ==.
So, try scan.nextLine().equals("").
You will have to look for specific pattern which indicates end of your input say for example "##"
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
if (line.equals("##")) {
System.exit(0);
scan.close();
}
}
} finally {
if (scan != null)
scan.close();
}
In this case, I recommend you to use do, while loop instead of while.
Scanner sc = new Scanner(System.in);
String input = "";
do{
input = sc.nextLine();
System.out.println(input);
} while(!input.equals("exit"));
sc.close();
In order to exit program, you simply need to assign a string header e.g. exit. If input is equals to exit then program is going to exit. Furthermore, users can press control + c to exit program.
You can check the next line of input from console, and checks for your terminate entry(if any).
Suppose your terminate entry is "quit" then you should try this code :-
Scanner scanner = new Scanner(System.in);
try {
while (scanner.hasNextLine()){
// do your task here
if (scanner.nextLine().equals("quit")) {
scanner.close();
}
}
}catch(Exception e){
System.out.println("Error ::"+e.getMessage());
e.printStackTrace();
}finally {
if (scanner!= null)
scanner.close();
}
Try this code.Your terminate line should be entered by you, when you want to close/terminate the scanner.
With this approach, you have to explicitly create an exit command or an exit condition. For instance:
String str = "";
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) {
//Handle string
}
Additionally, you must handle string equals cases with .equals() not ==. == compares the addresses of two strings, which, unless they're actually the same object, will never be true.
Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int is a double produces a double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args){
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("Hi temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}
You can check if the user entered an empty by checking if the length is 0, additionally you can close the scanner implicitly by using it in a try-with-resources statement:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter input:");
String line = "";
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNextLine()
&& (line = scan.nextLine().toLowerCase()).length() != 0) {
System.out.println(line);
}
}
System.out.println("Goodbye!");
}
}
Example Usage:
Enter input:
A
a
B
b
C
c
Goodbye!

How to repeat a question to a user until while loop condition is false?

I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}

Java Scanner delimiter and System.in

I have some problem when I ask the user to input some numbers and then I want to process them. Look at the code below please.
To make this program works properly I need to input two commas at the end and then it's ok. If I dont put 2 commas at the and then program doesnt want to finish or I get an error.
Can anyone help me with this? What should I do not to input those commas at the end
package com.kurs;
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
String gd = "4,5, 6, 85";
Scanner s = new Scanner(System.in).useDelimiter(", *");
System.out.println("Input some numbers");
System.out.println("delimiter to; " + s.delimiter());
int sum = 0;
while (s.hasNextInt()) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
s.close();
System.exit(0);
}
}
Your program hangs in s.hasNextInt().
From the documentation of Scanner class:
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
In a few words, scanner is simply waiting for more input after the last integer, cause it needs to find your delimiter in the form of the regular expression ", *" to decide that the last integer is fully typed.
You can read more about your problem in this discussion:
Link to the discussion on stackoverflow
To solve such problem, you may change your program to read the whole input string and then split it with String.split() method. Try to use something like this:
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(", *");
int sum = 0;
for (String token : tokens) {
sum += Integer.valueOf(token);
}
System.out.println(sum);
}
}
Try allowing end of line to be a delimiter too:
Scanner s = new Scanner(System.in).useDelimiter(", *|[\r\n]+");
I changed your solution a bit and probably mine isn't the best one, but it seems to work:
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
int sum = 0;
if (s.hasNextLine()) {
// Remove all blank spaces
final String line = s.nextLine().replaceAll("\\s","");
// split into a list
final List<String> listNumbers = Arrays.asList(line.split(","));
for (String str : listNumbers) {
if (str != null && !str.equals("")) {
final Integer number = Integer.parseInt(str);
sum = sum + number;
}
}
}
System.out.println(sum);
look you can do some thing like this mmm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
System.out.println("When did you to finish and get the total sum enter ,, and go");
boolean flag = true;
int sum = 0;
while (s.hasNextInt() && flag) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
}

When the program loops it prints the line "Enter your name (first and last): " twice?

So in the program I ask the user whether they want to rerun the program but when it does it prints the line "Enter your name," followed by a space, twice. Can someone please help me find the cause of this? It doesn't happen when you run it the first time by the way.
import java.util.Scanner;
public class PirateName
{
static Scanner input = new Scanner(System.in);
static String[]firstNames = {"Captain", "Dirty", "Squidlips", "Bowman", "Buccaneer",
"Two toes", "Sharkbait", "Old", "Peg Leg", "Fluffbucket",
"Scallywag", "Bucko", "Deadman", "Matey", "Jolly",
"Stinky", "Bloody", "Miss", "Mad", "Red", "Lady",
"Shipwreck", "Rapscallion", "Dagger", "Landlubber", "Freebooter"};
static String[]secondNames =
{"Creeper","Jim","Storm","John","George","Money","Rat","Jack","Legs",
"Head","Cackle","Patch","Bones","Plank","Greedy","Mama","Spike","Squiffy",
"Gold","Yellow","Felony","Eddie","Bay","Thomas","Spot","Sea"};
static String[]thirdNames =
{"From-the-West","Byrd","Jackson","Sparrow","Of-the-Coast","Jones","Ned-Head",
"Bart","O'Fish","Kidd","O'Malley","Barnacle","Holystone","Hornswaggle",
"McStinky","Swashbuckler","Sea-Wolf","Beard","Chumbucket","Rivers","Morgan",
"Tuna-Breath","Three Gates","Bailey","Of-Atlantis","Of-Dark-Water"};
static String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o",
"p","q","r","s","t","u","v","w","x","y","z"};
public static void main(String[] args) {
System.out.println("Welcome to the pirate name generator");
System.out.println("");
boolean running = true;
while(running){
nameGenerator();
}
}
public static boolean nameGenerator()
{
boolean rerun = false;
int x = 0;
System.out.println("Enter your name (first and last): ");
String userName = input.nextLine();
System.out.println("");
try{
String first = userName.substring(0,1);
for (int i=0;i <= 25 ; i++)
{
if(first.equalsIgnoreCase(letters[i]))
{
first = firstNames[i];
}
}
String last1 = userName.substring(userName.indexOf(' ')+1);
for (int i=0;i <= 25 ; i++)
{
if(last1.substring(0,1).equalsIgnoreCase(letters[i]))
{
last1 = secondNames[i];
}
}
String last2 = userName.substring(userName.length() - 1);
for (int i=0;i <= 25 ; i++)
{
if(last2.equalsIgnoreCase(letters[i]))
{
last2 = thirdNames[i];
}
}
System.out.println("Your pirate name is: ");
System.out.println("");
System.out.println(first+" "+last1+" "+last2);
System.out.println("");
System.out.println("Would you like to try again? (Type 1 for yes, 2- no)");
int a = input.nextInt();
if (a==2)
{
rerun = false;
System.out.println("Good Bye!");
return rerun;
}
else
{
rerun = true;
}
return rerun;
}
catch (Exception e){
System.out.println(" ");
}
return rerun;
}
}
I see at least three problems.
At the end of the method, when you read the value of a, you're pulling an integer from the Scanner, but you're not pulling out the newline character that follows the integer. This means that next time you call nextLine(), all you'll get is a blank line. The cure for this is to add an extra input.nextLine() immediately after input.nextInt().
You're catching exceptions and throwing them away, without even printing their stack traces. That means that if your program does encounter a problem, you'll never find out any information about the problem.
You're not using the value rerun outside the nameGenerator method. When you call it, you're checking if running is true, but running will never change, so you'll just go on calling it forever. So you probably want to change the code that calls it to this.
boolean shouldRun = true;
while (shouldRun) {
shouldRun = nameGenerator();
}
It looks like you are using the input scanner for entering both ints and strings. You should use two separate scanners, or change it so that input is brought in with .nextLine() and then changed to an integer.
The problem is you enter two characters when deciding to try again. The first is the int, the second is the character. The second character is not an integer, so it is left in the buffer. Then when you get input a second time, you are using a scanner that already has characters in the buffer. So it processes the buffer and reads the left over char as an empty line.
http://www.java-forums.org/new-java/24042-input-nextline.html

How to skip a block in Java?

In the program given I have to make sure that if two consequtive characters are the same. I shouldn't increase the value of the variable (Count)... I have tried "break;", but that skips me out of the "for loop" which is very counter-productive. How can I skip the given part and still continue the "for loop"?
Currently my output for "Hello//world" is 3. It should be 2 (the '/' indicates a ' '(Space)).
Code
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))==check) //This is the condition to prevent increase for
//count variable.
{
count = count; //This does not work and neither does break;
}
count++;
}
}
System.out.println("The number of words are : "+count);
}
}
You can use the keyword continue in order to accomplish what you are trying to do.
However you can also inverse your conditional test and use count++ only if it is different (!= instead of == in your if) and do nothing otherwise
if ((inp.charAt(j+1)) != check) {
count++;
}
The word you are looking for is "continue".
Try this:
if ((inp.charAt(j+1)) != check) {
count++;
}
Increment the value of count by checking with !=.
Try using continue where you want to skip an block.
Use "continue;" when you want to break the current iteration.
continue is a keyword in java programming used to skip the loop or block of code and reexecutes the loop with new condition.
continue statement is used only in while,do while and for loop.
You may want to use the continue keyword, or modify the logic a little bit:
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))!=check)
{
count++;
}
}
}
System.out.println("The number of words are : "+count);
}
}
Edit:
You may want to use the split method of the String class.
int wordsCount = str.split(' ').length;
Hope it helps :)
The following should work.
import java.util.Scanner;
class CountWordsWithEmergency
{
public static void main()
{
Scanner input = new Scanner(System.in);
System.out.println("Please input the String");
String inp = input.nextLine();
System.out.println("thank you");
int i = inp.length();
int count = 1;
for(int j=0;j<=i-1;j++) //This is the for loop I would like to stay in.
{
char check = inp.charAt(j);
if(check==' ')
{
if((inp.charAt(j+1))==check) //This is the condition to prevent increase for
//count variable.
{
continue;
}
count++;
}
}
System.out.println("The number of words are : "+count);
}
}

Categories