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;
}
Related
Here's the code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Number: ");
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
} else {
System.out.println("Not an integer.");
}
}
scanner.close();
}
When the value is an integer everything works fine, the loop breaks out, however when the input is not an integer I keep seeing this infinitely flooding the terminal:
Number: Not an integer.
Number: Not an integer.
Number: Not an integer.
...
...
...
The reason this is happening when using Scanner.hasNextInt() in conjunction with Scanner.nextInt() is because the nextInt() method does not consume the ENTER key strike from the scanner buffer (when you enter a number) so this ENTER keeps getting played indefinitely. You need to clear this out of the Scanner buffer (so to speak) and to do that, you need to do this:
} else {
System.out.println("Not an integer.");
scanner.nextLine(); // Clear Scanner buffer.
}
Another reason why I just use Scanner.nextLine() ;).
OH...and don't close the Scanner object unless you are sure your application is finished with it otherwise you will not be able to use it again until you restart your application. It is auto-closed and Garbage Collected when the application closes anyways.
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
}
Because scanner.hasNextInt() is looking for an Integer input and if the input is integer it prints its value and breaks (break statement) the while loop (i.e come out of the loop) else it keeps scanning for integer input.
Also you are using condition true in while loop which means loop will keep executing infinitely until we break it.
That's simply because:
You are not taking out the non integer element (so it doesn't advance)
There is no other logic to leave the loop (while(true) is not nice anyway) if there is no integer.
You have entered an infinite loop if your scanner object does not recognize an integer input. Since you are not having a "break" inside the else{} block, it would loop through infinite number of times and flood the terminal. Insert a "break;" after the print statement
add break; after System.out inside else bracket , so you can break your loop once you encounter a non-integer input.
while(true)
{
if(Something) // What Ever
{
break;
}
}
System.out.println("Something Happened");
so if something happens you'll see Something Happened Once.
Edit:
If you want it to repeat asking, change it like this:
public static void main(String[] args) {
Scanner scanner;
while (true) {
scanner= new Scanner(System.in);
System.out.print("Number: ");
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
} else {
System.out.println("Not an integer.");
}
}
scanner.close();
}
public void talk() {
String[] prompts = {"Describe to me in a sentence why this is a cool program.",
"Describe to me in a sentence how your day was.",
"Describe to me in a sentence what programming means to you.",
"Describe to me in a sentence why food is neccessary for humans."};
iramInLoop = true;
while(iramInLoop)
{
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if(!checkPunc(input) && !checkCaps(input)){
System.out.println("Check your capitalization and your punctuation!");
}
else{
System.out.println("Great grammar keep it up! Do you want to try again?");
if(input.equals("yes")) continue;
else
{
iramInLoop = false;
Raybot.talkForever();//this exits the loop
}
}
}
}
I am having extreme trouble trying to restart my loop. So at the end of my code when the loop is done running I put a string which asks if the user wants to try again and if the user says yes I want it to go back to the beginning of the loop and do what the loop does again. However, every time I run it it goes to the end of the loop and doesn't even ask for an input.
I think you should be breaking out of the loop if the person guessed right, but then decided not to continue. In this case, your logic should be something like this:
while (true) {
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if (!checkPunc(input) && !checkCaps(input)) {
System.out.println("Check your capitalization and your punctuation!");
}
else {
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
if (input.equals("no")) {
break;
}
}
}
// whatever this does, you intended for it happen after the loop terminates, so do it here
Raybot.talkForever();
You are missing to actually accept any input
maybe
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
change if(input.equals("yes")) continue;
to if(Raybot.getInput().equals("yes")) continue;
Why is that I can still an input even it's outside the while loop?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
while(true){
}
}
First, you don't need a while loop to take any input and your loop is practically useless since its not being used. Second, That loop is bad since any other loops you might have in your code will be unreachable. unless you specify a way to break the loop using break; or flags e.g.:
boolean myCondition = true;
while(myCondition){}
or use break:
while(true){
if(whatever){
break;
}
}
Then again you don't need any of this since your not dealing with multiple inputs etc. So your answer is NO its working how you told it to work.
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.
I'm new to programming and to this website, so here goes.
I wanted to write a program that would allow as many input strings as possible to be added to an ArrayList. So I used a while loop in the following code. What I intended was for the loop to break if the input was 0.
import java.util.*;
public class AddToList2
{
static Scanner q = new Scanner(System.in);
public static void main(String[] args)
{
ArrayList<String> inputlist = new ArrayList<String>();
while (true)
{
System.out.print("Enter something here: ");
String x = q.nextLine();
inputlist.add(x);
if (x.equals("0"));
break;
}
}
The program was compiled without error, but sadly, when I ran the program many times, the loop broke no matter what the input was. Any way to solve this?
Well, that was careless of me! Anyway, I had created that program in order to find out what was wrong with this:
ArrayList<String> endangeredlist = new ArrayList<String>();
ArrayList<Integer> popn = new ArrayList<Integer>();
while (true)
{
System.out.print("Name an animal: ");
String animal = q.nextLine();
endangeredlist.add(animal);
if (animal.equals("EXTERMINATE"))
break;
q.next();
System.out.print("How many are left in the wild? ");
int numberleft = q.nextInt();
popn.add(new Integer(numberleft));
}
(This is part of a much larger program.) My intention was for the loop to break when the animal name input was EXTERMINATE. Sadly the program throws a NoSuchElement exception if the input first time round was EXTERMINATE, and if I had inputted something else first the loop would start, but then inputting EXTERMINATE second time round does not break the loop. Why is that?
You have an extraneous semicolon after your if, which effectively makes it
if (x.equals("0")) { }
break;
You have a semi-colon at the end of your condition.
This turns the break into a statement of its own, without the condition.
Your if statement is broken
if (x.equals("0"));
This is basically saying if (x.equals("0")) do nothing...
This is one of the reasons why you should use parenthesis around your if statements
if (x.equals("0")) {
break;
}