Continue statement in Java - java

I adding a continue statement to end the current iteration so that the rest of the statement in the loop body is not executed.
public class Main {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
System.out.println(sum);
}
}
The things I can't understand is why I will get error if I added {} ?
public class Main {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11) {
continue;
sum += number;
}
}
System.out.println(sum);
}
}
Error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable code
at Main.main(Main.java:18)

This will work.
if (number == 10 || number == 11) {
continue;
}
sum += number;
Explanation
When you don't add {} to your if statement, only the next line will be considered. Therefore, you need to leave sum += number outside the {}

Because continue statement is final in your branch (between {}), so next statement (sum += number) will not execute never. Your IDE must warn you of that, that's why it didn't compile it and you got error.

In your first block, the one without { you effectively wrote:
if (number == 10 || number == 11) {
continue;
}
sum += number;
The sum += number is reachable, as long as the expression is false.
In the second you actually wrote:
if (number == 10 || number == 11) {
continue;
sum += number;
}
The sum += number; has become unreachable because if the expression is true it will always be skipped because of the continue, and if the expression is false it will not be executed because it is not in the block statement.

As other answers said correctly, only the first line of code will be run after an if statement. However, another rule is that you cannot add any more lines of code after the "continue" statement in an if statement. So, that is really the error. If you were to tweak the code to switch the "sum += number;" with continue, you won't receive the same error. Hope this helps.

You execute sum += number; inside curly brackets ({}) of your if-block:
if (number == 10 || number == 11) {
continue;
sum += number;
}
This will work:
if (number == 10 || number == 11) {
continue;
}
sum += number;

Related

Find the binary equivalent of integer in Java using a while loop

I'm new to Java. I've been writing code to find the binary equivalent of an integer in Java using a while loop. I've written the following code and it's not throwing any error, but it was not printing INVALID INPUT. It is printing the valid binary number of a given integer value. Can anyone suggest where and what I'm doing wrong? And how should I get the proper input?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if ((n >= 0) && n > 999) {
System.out.println("Invalid Input");
} else {
while (n > 1) {
if (n <= 999) {
System.out.println(Integer.toBinaryString(n));
break;
}
}
}
}
}
Change && to ||:
if (!(n >= 0) || n > 999) {
Or even better, express conditions without negation:
if (n < 0 || n > 999) {
Positive conditions, ie "a is b", are easier to read.
Why are you using a loop at all? You're just adding needless complexity. Your code can be re-written to this:
if (n >= 0 && n < 1000) {
System.out.println(Integer.toBinaryString(n));
return;
}
System.out.println("Invalid Input");
You haven't said if this is an assignment but typically it is done like this for such questions.
loop until value is 0
get remainder from division by 2.
prepend to string
divide n by 2 to expose next binary digit.
// get some input,
int n = 1249;
String s = "";
while(n != 0) {
s = (n%2) + s;
n/=2;
}
System.out.println(s);
prints
10011100001

Why can't I write a return statement inside a loop?

I'm writing a function that gives me the largest factor that is a prime number of a number. So for example, the number 12 will give me 3. My initial code was:
public static int getLargestPrime(int number) {
if (number < 2) {
return -1;
}
for (int num = 2; num <= number; num++) {
int mod = number % num;
if (mod == 0) {
int div = number / num;
if (div == 1) {
return number;
} else {
number = div;
num = 1;
}
}
}
}
But I keep getting a missing return statement error so I added one:
public static int getLargestPrime(int number) {
if (number < 2) {
return -1;
}
for (int num = 2; num <= number; num++) {
int mod = number % num;
if (mod == 0) {
int div = number / num;
if (div == 1) {
return number;
} else {
number = div;
num = 1;
}
}
}
return number;
}
It is now correct, but I don't quite understand the logic behind it. I have read that there are some situations that the loop will not execute hence I need to return something even if my loop does not execute however I cannot think of any situations where my loop will not execute. Literately anything 2 or above will trigger the loop and anything less than 2 will return -1. So my question is in what situations will the loop not execute? And also, the return statement after the for loop does not really make sense, is there a better way of solving the missing return statement?
In your initial code:
if (div == 1) {
return number;
} else {
number = div;
num = 1;
}
}
In case when you'll always have false, you will never reach return statement.
Compiler does not predict if it will actually happen so it requires return statements in both if and else blocks. So it actually has nothing to do with for loop.
Two suggestions
1. It is better not to change the parameter you passed ( In this case number variable)
2. Have as few return statements as possible.
In your case, you can declare another variable tempNumber outside the for-lopp and assigned with 'number'. In the if condition where you are returning, there you 'break'. Return the number at the end of the function. That way always number is returned
public static int getLargestPrime(int number) {
if (number < 2) {
return -1;
}
int tempNumber = number;
for (int num = 2; num <= tempNumber; num++) {
int mod = tempNumber % num;
if (mod == 0) {
int div = tempNumber / num;
if (div == 1) {
break;
} else {
tempNumber = div;
num = 1;
}
}
}
return tempNumber;
}
https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14
The Java compiler does not verify your code inside your loop, so you need to put return statement all of your forks.
Coverage tests will warn you because you have an unreachable code, so you need re-planning your code.
NOTE: you need check your prime test until or equals Math.sqrt(number), if larger than this sqrt without divider, you can break your loop and return the number
I cannot think of any situations where my loop will not execute
It is mandatory to write methods in a valid, well defined way. See it as a form to help the compiler.
The existence of a return statement is checked at compile time. If the compiler finds a possible execution branch that does not end in a valid return statement (or an explicitly thrown exception) it runs into an error. Read more.
Even ...
int method() {
if (true)
return 1;
}
... will fail to compile with
This method must return a result of type int

"exception in thread main / by zero" Error

my perfect number program has an error "exception in thread main / by zero" can someone help me find the error
public static void main(String[] args) {
int num = 6, sum = 0, rem = num;
while (rem != 0) {
rem--;
if (num % rem == 0) {
sum = sum + rem;
}
}
if (sum == num) {
System.out.println("It is a perfect number");
} else {
System.out.println("It is not a perfect number");
}
}
When you call while (rem != 0) and if rem == 1, decrementing it will be 0 and therefore you can't divide then.
So change while (rem != 0) to while (rem > 1) and it should work.
Example
If you know this % symbol finds the reminder of the division of the left number by the right number, so you should check if any time the right number was zero it raises this error, so in your program the rem variable decreases before you find the reminder because of that every time in the end of the loop this error happens, so you can fix that by changing the rem--; statement's location to the end of the loop like this:-
while (rem != 0) {
if (num % rem == 0) {
sum = sum + rem;
}
rem--;
}
So this time the loop doesn't repeat when the rems value was 0.
In your code at the 6th time of looping the rem variable value is 1, so your while loop condition will become true.
Inside while loop the remainder variable decreased to value zero, and the code (num%rem ==0) will lead to dividing by zero error, because the %operator is finding the remainder from 2 variables and at current situation the dividend is zero. So the code will throw the divide by zero exception.
Change the while loop condition to while (rem >1)
After above mentioned changes your code looks as below.
public static void main(String[] args) {
int num = 6, sum = 0, rem = num;
while (rem > 1) {
rem--;
if (num % rem == 0) {
sum = sum + rem;
}
}
if (sum == num) {
System.out.println("It is a perfect number");
} else {
System.out.println("It is not a perfect number");
}
}

Java program hangs in CMD but works just fine in JDeveloper. Why?

I am relatively new to Java and this would be my first post on this site.I have used it many times before, but this time I haven't found an answer to my problem so here I am..
This code works great in my IDE (JDeveloper) but for some reason, when I run it in CMD it hangs for certain parameters (ex. 7844578642 2;7844578642 16 - the two sets work in IDE but not CMD).
Any ideas what am I doing wrong?
class PR13_19 {
public static void main(String args[]) {
long N = 0;
int base = 0,pow = 1;
String result = "";
if(args.length != 2){
System.out.println("Please enter Number and base...");
return;
}
try{
N = Long.parseLong(args[0]);
base = Integer.parseInt(args[1]);
if(!(base >= 2 && base <= 16)) throw new NumberFormatException();
}catch(NumberFormatException | StringIndexOutOfBoundsException exc){
System.out.println("Invalid Input");
return;
}
//converts number N in base 10 to any base "base"
// if base >10 11=A,12=B,13=C....(ex.hexadecimal)
while(pow <= N/base)
pow *= base; //greatest power of "base" >= N
while(pow > 0){
if(N >= pow) {
if(N/pow > 9) result += (char)((N/pow) + 55);
else result += (N/pow);
N -= (N - (N % pow));
}
else result += "0";
pow /=base;
}
System.out.println(result);
}
}
You must enter a number defined in javas LONG scope or change the code.
You can also add try/catch clause to see which error occurs.

I'm getting an error with <= saying that it's an invalid AssignmentOperator + my code looks wack I think

So I got stuck with a whole lot of this:
package test;
import javax.swing.*;
import java.util.Random;
import java.util.Scanner;
public class GuessGame {
public static void main(String[] args)
{
Scanner keys = new Scanner(System.in);
System.out.println("Hello! Would you like to play?");
String choice = keys.next();
for (choice.equals("y"); choice.equals("yes");)
{
System.out.println("Awesome!");
choice = "";
Random bill = new Random();
int j;
j = bill.nextInt(50);
System.out.println("Guess what the number I'm thinking is ");
int number;
number = keys.nextInt();
for (number <= (j + 10); number >= (j - 10);)
{
System.out.println("Warm!");
number = 0;
number = keys.nextInt();
}
for (number = (j + 5); number == (j - 10);)
{
System.out.println("Hot!!!");
number = 0;
number = keys.nextInt();
}
}
for (choice.equals("n"); choice.equals("no");)
{
System.out.println("okay");
keys.close();
System.exit(0);
}
}
}
On the line with " for (number <= (j + 10); number >= (j - 10);)", I'm getting an error on the "<=", and I've got no idea how to make amends on it. As well, I'm not sure if I should be using the for statement for this. Please help me understand my mistake, and if there is a better alternate than for.
Thank you!
That is because the first parameter of the for statement is used for initialization of the variable, thus giving you an error.
documentation:
for (initialization; termination;increment) {
statement(s)
}
problem:
for (number <= (j + 10); number >= (j - 10);)
solution:
use an if statement if you are going to check both variable
if(number <= (j + 10) && number >= (j - 10))
Try replacing each of your for loops with if statements:
if (choice.equals("y") || choice.equals("yes") {
...
if (number <= (j + 5) && number >= (j - 5)) { ... } // I assume this is what you meant here
else if (number <= (j + 10) && number >= (j - 10)) { ... }
...
}
else {
System.out.println("okay");
keys.close();
System.exit(0);
}
Note that you want your most restrictive if statement first, so I changed the order for the part where you are checking if it is within certain ranges. This way it checks whether you are "hot" before checking whether you are "warm" (since hot is contained in warm).
Also note that the else if statement for checking "warm" means that if you are hot, it will not bother checking if you are warm and updating your output twice.
I also replaced the "no" case with just an else statement, which will catch any answer that is not "y" or "yes".

Categories