How do I process the last line when using `while(scanner.hasNextLine())`? - java

As the title states, right now I have something that looks like this:
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
string input = scanner.nextLine();
switch(input){
case 1:
do stuff;
break;
case 2:
do stuff;
break;
case 3;
printf("we're done here");
scanner.close();
System.exit(1);
}
}
Obviously, my actual code isn't this simple, but the general idea is the same.
The loops work, and it'll process every line until the last.
And here's the problem, it won't process the last line, the one that actually exits the program....
The answer is probably very simple, but I can't really think of it from the top of my head. How can I process the last line?

Try the below code it works, Use System.exit(0) should come outside switch.
Scanner scanner = new Scanner(System.in);
boolean flag = false;
while(scanner.hasNextLine()){
string input = scanner.nextLine();
switch(input){
case 1:
do stuff;
break;
case 2:
do stuff;
break;
case 3;
printf("we're done here");
flag = true;
break;
}
if(flag) {
System.exit(0); //try 'break' too.
}
}

You need to move the code for the last case statement to the outside of the while loop. The scanner won't have another line and the loop will break.

Related

How to break from the outer for loop

This program splits a list of strings to line by line. I want to stop/terminate the program after "halted" has been entered. But now it only terminates when "halted" is entered alone and not when it's in a list of strings. Any help is greatly appreciated:)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter words ");
while (true) {
String userText = scanner.nextLine();
if (userText.equals("halted")) {
break;
}
else {
String[] pieces = userText.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
if (pieces[i].equals("halted")) {
System.out.println(" Stop Program...");
break;
}
}
}
}
}
Just return; instead, or even System.exit (if you want to exit, then exit, don't attempt to break down the call stack 'nicely'. The computer will do it for you and will do it unfailingly, whereas if you try to break your way out each layer individually, you're writing lots of code, and you can mess it up).
break; without any further argument will find the 'closest' while, do, for, or switch that encloses the break statement, and is taken to mean: Break out of that thing.
You can use labelled breaks instead to break out of any statement or expression that can be braced:
outer:
while (true) {
...
if (pieces[i].equals("halted")) break outer;
}
It would be bad code style here though, just return;.
You are breaking the for loop, not while loop, that why the program still running, you can replace the for() with below code
if (Arrays.asList(pieces).contains("halted")){
System.out.println(" Stop Program...");
break;
}

How do I use user input in an if-else statement and how do I loop the code back around if the user input is not what is asked for?

(Any text now in this question is from after the answer to my question was selected)
This is the code given for my problem. I wanted the code to perform certain tasks whenever the user input "Yes" or "No", so I needed to know how to implement the user input into an if-else statement. I also wanted to find out how to loop the code back to the user input of anything other than "Yes" or "No" was entered.
import java.util.Scanner;
public class RandomPerkSelector {
public static void main(String [] args){
Scanner userInput = new Scanner(System.in);
System.out.println("Are you playing as a survivor?");
}
}
First you want to use your Scanner to read from the keyboard. You are already half-way there:
Scanner userInputReader = new Scanner(System.in);
String userInput = userInputReader.nextLine();
You can simply check if the userInput is equal to yes/no like this:
if(userInput.equals("yes")){ //note strings are compared with .equals, not ==
//"yes" case
}else if(userInput.equals("no")){
//"no" case
}else{
//neither "yes" nor "no"
}
Alternatively a switch statement also works
switch(userInput){
case "yes":
//yes case
break;
case "no":
//no case
break;
default:
//neither "yes" nor "no"
break;
}
Making it ask for more inputs if an invalid one was given:
while(true){
String userInput = userInputReader.nextLine();
if(userInput.equals("yes")){ //note strings are compared with .equals, not ==
//"yes" case
//generate your numbers for "yes"
break;
}else if(userInput.equals("no")){
//"no" case
//generate your numbers for "no"
break;
}else{
//neither "yes" nor "no"
//note that the continue statement is redundant and
//the whole else-block can be omitted
continue;
}
}
If you want users to input just "yes"/"no" and asking them to input again until they get it right, you can use a do while loop. After that, you can using a switch statements to control your program flow. Like this
Scanner sc = new Scanner(System.in);
String userInput;
do{
System.out.println("Input : ");
userInput = sc.nextLine();
}while("yes".equalsIgnoreCase(userInput)==false && "no".equalsIgnoreCase(userInput)==false);
switch(userInput){
case "yes":
//do something
break;
case "no":
//do something
break;
default:
//do something
break;
}

java currency calculator pausing swtich to give output back to user

first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.

Magic 8-ball program

I have an assignment for my Java class to program a Magic 8-ball. It is supposed to generate a random number for the response, contain a "while(true)" statement, and a switch statement for the replies. This is what I have so far. I can't seem to figure out how to work the "while(true)" statement in without it repeating infinitely.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String question;
int retry;
int q1;
System.out.print("What is your question for the Magic 8-bit 8-ball? ");
question = input.next();
System.out.print(process());
/*This is where I am having the problem. How do I work a "while(true)" in
* to where this won't infinitely repeat?
*/
}
public static int process() {
Random rand1 = new Random();
int random = rand1.nextInt(9);
int ans = random;
switch (ans) {
default: System.out.println("Does not compute!! Error! Error!");break;
case 1: System.out.println("The answer is.............. 42");break;
case 2: System.out.println("To get to the other side!!!");break;
case 3: System.out.println("Out of memory! Try again!");break;
case 4: System.out.println("Who do you think I am, IBM's Watson?");break;
case 5: System.out.println("Danger Will Robinson!! Danger!!");break;
case 6: System.out.println("What do you think?");break;
case 7: System.out.println("Fatal error.....nahhh just kidding");break;
case 8: System.out.println("Well, this is fun....NOT!");break;
case 9: System.out.println("Um...... 1,000,000,000,000,000,000,000?");break;
}
return ans;
}
}
Hum, the point of a while (true) loop is to be infinite, unless you add a break statement in it.
while (true) {
doStuff();
// if someCondition is true, this will exit the loop
if (someCondition)
break;
}
Note that this is equivalent to
do {
doStuff();
} while (!someCondition);
or
boolean someCondition = false;
while (!someCondition) {
doStuff();
}
It is usually preferrable to not have an infinite loop (while (true) for example) and have an explicit condition instead. Some exceptions exist, for example if the condition is complicated to express or if you want to break the loop at a particular position of the loop and not at the beginning or at the end :
while (true) {
doStuff();
if (someCondition)
break;
doSomeOtherStuff();
}
One of the many possible ways:
Create a a char and assign it to 'Y' (i.e. char continueLoop = 'Y').
Use this to control the while statement (i.e. while(char == 'Y') ).
Ask the user for input and process the input (i.e. System.out.println("Continue? Y/N") and then use Scanner to read the input and assign it to continueLoop.
You can create something similar using booleans.

system.in.read miss execution

Why after the first loop, the switch will execute twice before it stop to wait for my input? Is there any char left in the standard input? How can I fix the issue?
while(true)
{
int choice = System.in.read();
switch(choice)
{
case '1':
break;
default:
break;
}
}
InputStream#read only reads a single byte and will not consume the newline character (will be 2 characters, LF and CR on Windows platforms), passing it through to the next read. This read will now not block having received input and the flow will fall through to your default case.
You could use a BufferedReader instead and read a full line:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
...
int choice = Integer.parseInt(br.readLine());
By taking the time to read the documentation you would have noticed that this method takes in a single byte of data. If you hit Enter after you type in the data, then that will add another byte to the System.in stream, meaning the Switch statement has more data to work with.. You should use a Scanner to read streams like this.
Example
Scanner s = new Scanner(System.in);
// Create a scanner object that reads the System.in stream.
int choice = s.nextInt();
// Accept the next int from the scanner.
switch(choice)
{
// Insert selection logic here.
}
If you again print choice somewhere, probably you will get 10 and 13.
'10' is LF (line feed control char).
'13' is CR (carriage return control char).
This is why the switch is executing twice.
And the better way of taking input already have been shown by Reimeus, Chris Cooney.
You can use Break to Labeled Statement in this case. for more information http://www.javaspecialists.eu/archive/Issue110.html
Here is workign code:
import java.io.IOException;
public class Switch {
public static void main(String[] args) throws IOException {
exitWhile: {
while (true) {
System.out.println("type>");
int choice = System.in.read();
switch (choice) {
case '1':
break;
default:
System.out.println("Default");
break exitWhile;
}
}
}
}
}
This is an Infinite Loop. It will just keep taking the input.
You should be using a Scanner to get your input, than System.in.read(), like this:-
Scanner s = new Scanner(System.in);
while(true)
{
int choice = s.nextInt();
if(choice == 1){
break;
}
}
s.close();

Categories

Resources