I'm putting together a code for a hailstone sequence I found in an online tutorial, but in doing so I ran into an unreachable statement error. I don't know if my code is correct and I don't want advice in correcting it if I'm wrong(regarding the hailstone sequence, I want to do that myself..:) ). I just want help in resolving the "unreachable statement" error at line 19.
class HailstoneSequence {
public static void main(String[] args) {
int[][] a = new int[10][];
a[0][0] = 125;
int number = 125;
for (int i = 0;; i++) {
for (int j = 1; j < 10; j++) {
if (number % 2 == 0) {
a[i][j] = number / 2;
number = number / 2;
} else {
a[i][j] = (number * 3) + 1;
number = (number * 3) + 1;
}
}
}
for (int i = 0;; i++) {
for (int j = 0; j < 10; j++) {
System.out.println(a[i][j]);
}
}
}
}
This is an infinite loop:
for(int i=0;;i++){
Whatever comes after it never get executed (i.e. is unreachable).
In your first for loop:
for(int i=0;;i++){
....
}
You do not define the ending condition. e.g.
for(int i=0; i<10; i++){
....
}
Therefore the loop never exits.
Your first infinite loop of for(int i=0;;i++) stops any other code from being reached.
There is an infinite loop # line 7
You forgot to set an exit condition
for(int i=0;here;i++){
This might create unexpected behaviour.
Your first for statement (in the 6'th line) is an infinite loop therefore it stops further code to be reached.
for(int i=0;;i++)
You have problem at line number 6 in your first for loop.
for(int i=0;;i++) {
Here since your don't have any exit conditions, code is going in the infinite loop and the loop never exits. Whatever outside the scope of this for loop will be unreachable since your first loop is never existing.
Consider adding the exit condition (such as break or return etc.) inside your for loop to prevent this behavior.
Related
The code shown below is designed to generate 30 different numbers in the range of 36 using nested for loop.
This example shows that when it break from the inner for loop, it would execute the "update" (in this example the "update" is ++i) in the outside "for" loop. But my teacher told me that it wouldn't.
But when I debug it, it did execute the "update".
Am I correct?
public class array {
public static void main(String[] args) {
int a[] = new int[30];
for( int i=0;i<a.length;++i)
{
a[i] = (int)( Math.random()*36 ) +1;
for(int j=0;j<i;++j)
{
if(a[i]==a[j])
{
--i;
break;
}
}
}
for( int num: a) System.out.print( num+" " );
System.out.println();
}
}
That break breaks the inner loop. The outer loop continues with the update section of the for (++i). If your teacher told you it wouldn't do that ++i, he/she is mistaken. The inner update (++j) is not performed if that break is executed, but the outer one is.
Just to be clear we're talking about the same things:
int a[] = new int[30];
for (int i = 0; i < a.length; ++i) {
// Outer update ----------^^^
a[i] = (int) (Math.random() * 36) + 1;
for (int j = 0; j < i; ++j) {
// Inner update ---^^^
if (a[i] == a[j]) {
--i;
break; // <==== This break
}
}
}
for (int num : a) {
System.out.print(num + " ");
}
System.out.println();
The break keyword breaks only the inner loop, the outer loop still executes as expected and ++i takes place.
If your teacher said otherwise, he/she probably made a mistake.
Here's another demonstration:
//outer loop
for(...){
//inner loop
for(...){
if(...){
break;
}
}
}
If the condition in the if-body is satisfied, the inner loop breaks but the outer loop still continues as expected.
I hope this helps.. Merry coding!
Here is my code :
private String SerialNo;
private String FirmVersion;
public String GetSerial(int[] Data){
System.out.println("GetSerial Debug : Data => "+Data);
for (int i = 2;i==13;i++){
System.out.println("In the FOR => ok ");
if (i != 9){
SerialNo = SerialNo + Data[i];
}
if (i == 9){
SerialNo = SerialNo + ".";
}
}
System.out.println("SerialNo => "+ SerialNo);
return SerialNo;
}
My problem : I can't "enter" in the FOR
So my sysout of "In the FOR => ok", never shows and all the "actions" aren't done.
What am I doing wrong ?
ps : I'm sure that I'm compiling the right file.
The loop condition is never satisfied; i = 2 in the begin, the first check would fail, so all the loop would fail. Maybe it should be changed for:
for (int i = 2; i <= 13; ++i)
Examine your for statement:
for (int i = 2; i==13; i++)
This actually means the following:
assign 2 to i
Check whether i equal to 13. If yes, continue loop, exit otherwise.
Since i is not 13 in the first iteration of loop you never enter it. I believe that you wanted to write
for (int i = 2; i <= 13; i++)
In this case you will iterate from 2 to 13 inclusively. The condition of for loop means "do I have to remain iterating?" and not "do I have to escape?"
Change for (int i = 2; i == 13; i++) to for (int i = 2; i <= 13; i++).
The second argument is the loop condition which has to be true to run the loop.
Your condition became false at first iteration so control never goes to loop body.
for loop syntax:
for(initialization; condition; increment/ decrement){
//your code
}
So here you will have to use some appropriate condition to enter into the loop.
So for example :
for (int i = 0; i <= 13; i++) // for 0 to 13 increment
or
for (int i = 10; i >= 0; i--) // for 10 to 0 decrement
for (int i = 2;i==13;i++){}
It enters but failed at first condition check and for-loop exits.
It should be -
for (int i = 2;i<=13;i++)
You have initialized i=2
for (int i = 2;i==13;i++)
And condition is i==13 which will become false ultimately flow never enter into for loop
try to change the code like this
for (int i = 2;i<=13;i++)
Statement is not good should be like the one below:
for (int i = 2; i<13; i++) or for (int i = 2; i<=13; i++)
See compared simple while loop in the case of your for loop.
Think about int i =2; value set and i == 13 condition
Do you think it will work?
for (int i = 2;i==13;i++){
//do something
}
Same to below *while loop* explanation
int i = 2;
while (i == 13) {
//do something
i++;
}
I am sure it will work
for (int i = 2;i < 13;i++){
//do something
}
Same to below **while loop**
int i = 2;
while (i < 13) {
//do something
i++;
}
The flow of the for loop is: init statement-> condition check-> goes inside loop or outside depending on the condition outcome.
Here, since you've said i=2 ,then i==13 is false; it'll never go inside the loop.
You could use the ?: operator in the for loop and then modify your if statements a bit I guess..
How do I rewrite this as a while loop and as a for loop?
public void invertPicture()
{
Pixel[] pixelArray = getPixels();
for(Pixel p : pixelArray){
p.setRed(255-p.getRed());
p.setGreen(255-p.getGreen());
p.setBlue(255-p.getBlue());
}
}
Hint for your homework:
for (int i=0; i<myArray.length; ++i) {
myArray[i].doSomething();
}
I leave the while as an exercise, it is very similar: declare i outside the loop, increment i within the loop.
Well, your code is already in a for loop. However, I will show you another way to do a for loop and a while loop.
For Loop:
for(int i = 0; i < pixelArray.length; i++){
pixelArray[i].setRed(255 -pixelArray[i].getRed());
pixelArray[i].setGreen(255 - pixelArray[i].getGreen());
pixelArray[i].setBlue(255 - pixelArray[i].getBlue());
}
While Loop:
int i = 0;
while(i < pixelArray.length){
i++;
pixelArray[i].setRed(255 -pixelArray[i].getRed());
pixelArray[i].setGreen(255 - pixelArray[i].getGreen());
pixelArray[i].setBlue(255 - pixelArray[i].getBlue());
}
Also: A For Loop is just a easier to implement while loop.
I am in a beginner Java class and for a project I need to count how many times a condition returns TRUE(correctGuess) or FALSE(incorrectGuess) with a loop inside of a loop. The problem that I'm having is that the variables being incremented within the inner loop do not hold their incremented value as the loop reiterates. Therefore, the outer while-loop's condition is never false. I'm really new to programming and I can't figure out the solution. Thank you in advance for your time with this silly question and if there are any questions I would be happy do a better explanation. The code looks like this:
int incorrectGuess = 0;
int correctGuess = 0;
while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {
//Gets the users first guess
System.out.print("Please guess a letter [A-Z]: ");
letterGuessed = keyboard.nextLine();
for (int i = 0; i < WORD_LENGTH; i++){
char value = wordLetterArray[i];
String letterArray_value = String.valueOf(value);
if(letterGuessed.equals(letterArray_value)){
++correctGuess;
}
else
System.out.println("Bad comparison!");
if(i == WORD_LENGTH)
++incorrectGuess;
}
}
Looks like you may need to redesign the whole algorithm, but I can tell you what your main issue is with this looping forever:
// Seems legit
while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {
// Still seems legit
for (int i = 0; i < WORD_LENGTH; i++)
// Well, there's a problem, i will never be equal to word length
//because a condition of the for loop is i < WORD_LENGTH
if(i == WORD_LENGTH)
++incorrectGuess;
Again, I feel you need to redesign your whole algorithm, but if you want it to continue, just pull the incorrectGuess increment line out of the for loop. This will give you the intended result:
for (int i = 0; i < WORD_LENGTH; i++){
char value = wordLetterArray[i];
String letterArray_value = String.valueOf(value);
if(letterGuessed.equals(letterArray_value)){
++correctGuess;
}
else {
System.out.println("Bad comparison!");
}
}
incorrectGuess++;
I have come across a somewhat annoying problem during a project. I created this sample class to describe the issue which I am having.
public class Test {
public static void Testing(){
for (int i = 0; i >= 5; i++) {
System.out.println(i);
}
System.out.println("hello world.");
}
public static void main(String[] args) {
Testing();
}
}
My issue is that the only output from this program is simply "hello world."
Could anyone explain the reason why my println statement inside the for loop is being completely ignored? I have searched on Google but it is hard to describe in a search.
Thanks a lot!
The for loop should be
for (int i = 0; i <= 5; i++)
Hai Buddy. the problem is logical.look at the for loop closely for (int i = 0; i >= 5; i++)
The for loop should be
for (int i = 0; i <= 5; i++)
I think the problem is that you loop never executes since your condition is that I is at least 5, but you start it at zero. Try changing it to be less than or equal to five and see if that fixes it.
change the for loop
for(int i = 0; i <= 5; i++)
read again:
for (int i = 0; i >= 5; i++)
i defaults to zero, and the for iterates while i is more or equal to 5.
Because your condition (i >= 5) never is true, since you set i to 0. The condition should be i <= 5.
for (int i = 0; i <= 5; i++) //You have put > sign it should be < sign
{
System.out.println(i);
}
The reason is that your for loop is never executed. On first step i = 0 i>=5 = false so the body of the for is never executed
When main method invoke you method it first initialize the value of i with 0 then its go for the condition i>=5, Which looks like 0 >= 5 which always be 'false'.So you inner print statement never be execute.
The for loop never execute because the at the beginning i is checked to see if it equal or greater than 5 (which it is not, i=0)
for (int i = 0; i >= 5; i++)
then the loop terminates and the next statement is executed.