java break loop not working [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a break label in my java code but it doesn't jump to the label when I go to the break statement in my code:
OUTERMOST:for(String s :soso){
if(wasBreaked){
//code never enters this loop
Log.e("","WASBREAK = FALSE");
wasBreaked = false;
}
if(true){
Log.e("","WASBREAK = TRUE GOING TO OUTERMOST");
wasBreaked = true;
break OUTERMOST;
}
}

Break statement is not really a goto statement as in other programming languages like C.
What your code does instead is, break from the loop which has label OUTERMOST. I would have thought you need continue OUTERMOST; instead of break. But to me it really doesn't makes sense as you dont have further any statement post continue (now break in your code) and it's going to continue anyways irrespective of whether you say explicitly continue or not.

public class Test {
public static void main(String[] args) {
String soso[]={"1","2"};
boolean wasBreaked=false;
OUTERMOST:for(String s :soso){
if(wasBreaked){
Log.e("","WASBREAK = FALSE");
wasBreaked = false;
}
if(true){
Log.e("","WASBREAK = TRUE GOING TO OUTERMOST");
wasBreaked = true;
System.out.println("before break");
break OUTERMOST;//use continue in place of break here for going to label
}
System.out.println("Inside outermost loop");
}
System.out.println("outside outermost loop");
}
}
I tried this and it works
it gives output
before break
outside outermost loop
For going back to label you should use continue keyword rather than break in code. After using continue the output will be like
before break
before break
outside outermost loop

Related

How to read Multiple line input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to read multiple line input like a copy past input, but I can't end the while loop to stop reading. Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input =null;
while(sc.hasNext()) {
input=sc.next();
}
String [] split = input.split(" ");
for(int i = 0;i<split.length;i++) {
for(int j = split[i].length()-1;j>=0;j--) {
System.out.print(split[i].charAt(j));
}
System.out.print(" ");
}
sc.close();
}
}
Use buffer reader class, by this you'll be able to take multiple inputs at the same time.
https://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html
The hasNext() method will look if there is something to read. To do so it might block and wait on the used InputStream as described in the documentation of hasNext():
public boolean hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
When the InputStream ends it will return from the hasNext() call and return false, since there is no token to read (and the source of data/bytes is closed). But since you are reading from the keyboard via System.in there is no "end" of input because you still can enter new text into your application, which your while() loop will read.
There are several solutions for this:
Depending on how you start your java application, you can press CTRL-D to explicit close the so called "STDIN" stream which is "attached" to your keyboard input. That way the stream System.in will end and no further data can be read. This is also detected by the Scanners hasNext() method, which will return false at that point.
You can call your java application where you provide the data for the "STDIN" stream via a file or via other commands. Examples of these are: echo "data" | java Main or java Main < inputData.txt (depending on the terminal/console you are using).
Add an end marker to your content and look for it. When you place a text like "MY_TEXT_END" in your data and look for it you can use a simple equals() check inside the while() loop and stop reading when you have seen your marker "MY_TEXT_END".
Since you are using while loop and it will loop/execute through a block of code as long as a specified condition is true/met.
And here you are checking any condition to exit the loop.This method may block while waiting for input to scan and the scanner does not advance past any input.
Another gap that I see is, you are re-assigning the input to input var again and again without performing any operation beforehand accepting next line.
You can get more clarity on exiting the while loop here :
How to get out of while loop in java with Scanner method "hasNext" as condition?
Scanner sc = new Scanner(System.in);
String input = null;
while(sc.hasNext() && !(input = sc.next()).equals("exit")) {
System.out.println(input);
}
sc.close();
So, to answer your question, you must provide some check/exit condition for while loop to in-validate and exit out of the loop.

I need to rewrite Java "for" to "while" and "do" [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
i made a "for" a while a back ago now i need to change it to a "While" and change that to a "do", any help would be appriciated
for(int i = 3; i <= 10; i++) {
System.out.print(" " + i);
if(i % 10 == 0)
System.out.print("\n");
}
System.out.println();
}
}
A for statement:
for (ForInit; Expression; ForUpdate) Statement
is equivalent to the while statement:
{
ForInit;
while (Expression) {
Statement;
ForUpdate;
}
}
Converting a for to a while is simply a matter of cutting+pasting into this template.
for loops don't map onto to a do/while cleanly, because the Expression needs to be evaluated before Statement. You could do this:
{
ForInit;
do {
if (!Condition) break;
Statement;
ForUpdate;
} while (true);
}
but that's just horrible; you should be using a while statement instead.

Prevent program from getting terminated after exception handling [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Is there anyway to handle the exceptions in Java and prevent the program from getting terminated? For instance when the user enters an invalid number into a calculator, zero in this example for division in the denominator, I don't want the program to get terminated and show the handled exception message. I want the program to continue and ask for another input.
Could anyone clarify it with a practical example for me?
Simple: put a loop around the whole try catch block; like:
boolean loop = true;
while (loop) {
try {
fetch input
loop = false;
} catch (SomeException se) {
print some message
}
does the job in general.
Try this:
boolean exceptionOccured;
do {
try {
exceptionOccured = false;
// code to read input and perform mathematical calculation
// eg: a = 10/0;
} catch(Exception e) {
exceptionOccured = true;
System.out.pritnln("Invalid input! Please try again");
} finally {
// some code that has to be executed for sure
}
} while(exceptionOccured);
First the code inside the try block will be executed. When an execption occurs (like division by zero), execution of code jumps from try block to catch block where you can write your logic to loop the try-catch block.

Java: Displaying all elements from an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have created a String method that uses a loop to return all data elements of an object. The problem is, since it is a return statement, it will go through the loop once and then exit the method once the return statement has been executed.
I have looked over StackOverflow and the internet and have not been able to assist myself into figuring out this problem.
Code:
public String display()
{
for (int i=0; i<count; i++) //assume count has the value of 3
{
return "Name: "+item[i].getName(); //this is the issue; only loops once, then exits method
//also assume that an object item[] has been initialised with 3 positions
}
}
This is a common problem that people encounter with the return statement. In situations such as this I generally create a new String and have it return that. For example:
public String display()
{
String s = "Name: ";
for (int i = 0; i < 3; i++)
{
s = s + item.getName();
}
return s;
}
That way, you are actively adding onto a new string that you plan to return later. This method has proved extremely helpful for me, not only with strings but also with integers and ArrayLists. Because return statements result in the exiting of your code, you are going to want to try and keep them at the end of your methods unless you have some specific reason for having the return statement earlier in the method.
you are returning within loop, so as soon as it executes that return statement it will return from method without further iterating through loop
use StringBuilder to append() content and at the end (after loop) return built String
The reason your code was not working is that it was returning as soon as you reached the statement in the loop. Functions have return values, and in java, the return "x" statement returns the value "x" to the previous statement.
Say you wrote in your code
entireArray = display();
When that statement is reached during execution, the display method is called. The code then jumps to the display method. When the display method is called, it jumps into your loop. At the first line, it sees return "Name: "+item[i].getName(); This gets the name of the first item, appending it behind "Name: ". The function then returns to the previous line, entireArray = display();
Basically, display() is then replaced with the return value of the function. If you want to make sure everything is included, model your code off of something like this:
public String display() {
String total = "Name: ";
for (int i = 0; i < item.length; i++) {
total += item[i].getName();
}
return total;
}
This makes sure that every item's name in the "item" array is returned.
I would recommend that you read up a bit about call stacks http://en.wikipedia.org/wiki/Call_stack. This will help explain how functions return values, and why your original code did not work.

Program terminating before if statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm having trouble initializing an if statement in this program. The program terminates before running the if statement every time. Can anyone tell me what exactly I'm doing wrong?
import java.util.Scanner;
public class attempt1 {
public static void main (String [] args) {
Scanner console = new Scanner(System.in);
String userInput;
boolean done=false;
System.out.println("say something");
userInput=console.nextLine();
if (userInput.equals("stop")) {
done=true;
}
while(done=false) {
System.out.println("it worked!");
}
}
}
I think you want something like this:
public static void main (String [] args) {
Scanner console = new Scanner(System.in);
String userInput;
boolean done=false;
while(done==false) {
System.out.println("say something");
userInput=console.nextLine();
if (userInput.equals("stop")) {
done=true;
}
}
System.out.println("it worked!");
}
This code asks the user to keep saying something until they say stop at which point it prints out "it worked!"
The program will wait for your input every time you call userInput=console.nextLine(); It's not terminating, but just waiting for input.
Also, you want == in your while comparison. == compares values while = assigns
Use do-while here, it would be easier:
Scanner console = new Scanner(System.in);
String userInput;
do {
System.out.println("say something");
userInput=console.nextLine();
if(userInput.equals("stop"))
break;
} while(console.hasNextLine());
Instead of this construct
if (userInput.equals("stop")) {
done=true;
}
while(done=false) {
System.out.println("it worked!");
}
I suppose you wanted to say:
done = userInput.equals("stop")
if (!done) {
System.out.println("it worked!");
}
I'm not sure what was the purpose of while but you certainly didn't want to use a loop in this case.
You are using a scanner. If the user doesn't enter any data, the program won't run. Try running it with a preset string or int or whatever you need. The code looks fine
I see a couple of problems here.
Are you certain that there is a next line? To be sure:
System.out.println(console.hasNextLine())
Also, your boolean is incorrect. Remember that a single '=' is an assignment, and '==' means "is equal to".
You have an infinite loop.
while(done=false) {
System.out.println("it worked!");
}
This crashes the program. Just simply change while(done=false) to "else if (!done)".

Categories