Multiple error: class, interface, or enum expected - java

public static boolean prime(int n){
if(n<=1)
return false;
int z=2;
if(n==2)
return true;
while(z<Math.sqrt(n)){
if(z mod n==0)
return false;
z++;
}
return true;
}
Any clues what is wrong with my code?
I am receiving 7 errors of "class, interface, or enum" expecting...

You cant execute stand alone code, everything must exist in a class, interface or enum.
This needs to live inside a class. This should be in a file called MyClass.java
E.g.
public class MyClass {
public static boolean prime(int n){
if(n<=1)
return false;
int z=2;
if(n==2)
return true;
while(z<Math.sqrt(n)){
if(z mod n==0)
return false;
z++;
}
return true;
}
}
It can then be called by running MyClass.prime(7);
As mentioned by others, mod is also an invalid keyword and should be replaced by the % operator

If this is all of your code, you will need to enclose it in a class as the error indicates :)
Secondly, there's no mod keyword in Java, replace with %. Putting the 2 together:
public class MyPrimeTest {
public static void main(String[] args) {
boolean primeCheck = prime(43);
...
}
public static boolean prime(int n) {
if (n <= 1) {
return false;
}
int z = 2;
if (n == 2) {
return true;
}
while (z < Math.sqrt(n)) {
if (z % n == 0) {
return false;
}
z++;
}
return true;
}
}
Classes
Modulo operator

"class, interface, or enum expected" error occurs mostly due to missing {} curly brackets. Check your program thoroughly.
If the above mentioned is all your code,then you should encapsulate it within a class.
Dont forget to write main() too.
There is no 'mod' keyword in java. Use '%' instead.
import java.util.*;
class Prime
{
public ...........main(.... args[])
{
//accept integer
if(prime(n))//calling prime()
..
}
and then your method..
Cheers!

Related

Java beginner exercise with methods

I am real beginner in Java and I have one simple exercise where I need to convert m/h into km/h using a method and a return from it.
I have to define 2 situations: if km/h < 0 return -1 (error) and if km/h > 0 return km/h * 1.609 (value in m/h).
I tried everything I could think of but I either get a no return statement error or no output when I try to run it.
I can't understand why even if I gave it more than one return option it just doesn't work whatever the value is. I could use System.outprintln or String but the exercise specify I must use a return method.
here is my code, written in IntelliJ:
package EXERCISE;
public class Main {
public static void main(String[] args) {
toMilesPerHour(0);
}
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour > 0) {
return kilometersPerHour * 1.609d;
}
else if (kilometersPerHour == 0) {
return 0;
}
return kilometersPerHour * 1.609;
// if I don't write return here it gives me no return statement error,
// if I write it, it gives me no output with value > or < 0 but no error.
}
}
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else {
return kilometersPerHour * 1.609;
}
}
Try it like this:
public static double toMilesPerHour(double kilometersPerHour) {
return (kilometersPerHour > 0 ? kilometersPerHour*1.609 : -1;
}
You could also throw an exception if speed is negative:
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) throw new IllegalArgumentException("speed cannot be negative");
return kilometersPerHour*1.609;
}
Even if you use a method, you have to print the returned value:
package EXERCISE;
public class Main {
public static void main(String[] args) {
System.out.println(toMilesPerHour(0));
}
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour > 0) {
return kilometersPerHour * 1.609d;
}
else if (kilometersPerHour == 0) {
return 0;
}
return kilometersPerHour * 1.609;
//if I don't write return here it gives me no return statement error,
//if I write it, it gives me no output with value > or < 0 but no error.
}
}
Furthermore, you can get rid of the return statement at the end:
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else {
// you don't need to check if kilometersPerHour is 0, since every number multiplied with 0 is 0
return kilometersPerHour * 1.609;
}
}
If you use if()... else you have exactly two options. Either you go into the if clause and do whats there, or you go into the else clause. If if-clause and else-clause both have a return-statement, everything goes fine.
But you don't have if-else-clauses! You have if-else-if-clauses!
If the if-clause doesn't hold, you go into the else-clause, which again has an if-clause and so on. Finally you don't have a default else clause.... if you don't get into the first if-clause, you check in the else-clause, if the condition holds. If not, you check the condition in the next else clause. The last return-statement finally is the default else clause. We all, as humans, see, that every condition (<, == >) is covered, but the compiler doesn't see that!
The reason compiler gives you "no return statement" error is because you didn't cover all possible cases with your ifs: there is Double.NaN, which is not equal to 0 (or any other value, for that matter, including itself) and neither greater nor lesser than 0.
Also, compiler doesn't analyze your code deep enough to check if you covered all possible variants anyway: if you replace double with long, the result is the same - the compiler will see the reachable branch that doesn't return anything, and so it produces an error.
To fix an error, you need to have all branches return something:
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour == 0) {
return 0;
}
// Note: I don't have explicit check for NaN,
// because any arithmetic on NaN produces NaN,
// which would be the correct result for this function.
// So I let the "*" operator to check for NaN instead.
return kilometersPerHour * 1.609;

Given an array of numbers, the task is to print only those numbers which have only 1, 2 and 3 as their digits

Im currently working on a program to given integer input from user, print only those ones contain numbers 1 2 or 3. Here is my code so far:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int[] x=new int[5];
System.out.println("Enter 5 integers: ");
for(int i=0; i<x.length;i++) {
x[i]=s.nextInt();
boolean temp=recursion(x[i]);
if(temp==true) {
System.out.print(x[i]);
}
}
}
public static boolean recursion(int y) {
if(y%10==1 || y%10==2 || y%10==3) {
return true;
}
else if(y%10==0) {
return false;
}
else {
int remain=y/10;
recursion(remain);
}
}
So my approach is quite simple, I used a simple bool recursion to return true or false, true if it does contain 1 2 or 3 and false if not. The problem I am having is that I am not returning anything in my recursion else statement. I know I have to return something but not sure what to return or if its necessary. Anything I can change to make this work?
Your base cases for recursion are a little off, so in the statement
else if(y%10==0), the number 100 would cause this to fail even though it is valid. you want your false base case to actually be else if (y == 0) which means you have gone through the entire number. the solution looks like:
public static boolean recursion(int y) {
int positive = Math.abs(y);
if(positive%10==1 || positive%10==2 || positive%10==3) {
return true;
} else if (positive == 0) {
return false;
}
return recursion(positive / 10);
}
edit: Calling absolute value on the number makes it work for negative numbers as well, but you can call abs on the integer being passed in to the same effect.
I think you just have to do
return recursion(remain);
Use below code, hope this will help.
public static boolean recursion(int y) {
if(y%10==1 || y%10==2 || y%10==3) {
return true;
}
else if(y%10==0) {
return false;
}
else {
int remain=y/10;
return recursion(remain);
}
}

Return multiple values from void and boolean methods

I have the following problem: Having a boolean static method that computes similarity between two integers, I am asked to return 4 results:
without changing the return type of the method, it
should stay boolean.
without updating/using the values of external variables and objects
This is what I've done so far (I can't change return value from boolean to something else, such as an int, I must only use boolean):
public static boolean isSimilar(int a, int b) {
int abs=Math.abs(a-b);
if (abs==0) {
return true;
} else if (abs>10) {
return false;
} else if (abs<=5){
//MUST return something else, ie. semi-true
} else {
//MUST return something else, ie. semi-false
}
}
The following is bad practice anyway, but If you can try-catch exceptions you can actually define some extra outputs by convention. For instance:
public static boolean isSimilar(int a, int b) {
int abs = Math.abs(a-b);
if (abs == 0) {
return true;
} else if (abs > 10) {
return false;
} else if (abs <= 5){
int c = a/0; //ArithmeticException: / by zero (your semi-true)
return true;
} else {
Integer d = null;
d.intValue(); //NullPointer Exception (your semi-false)
return false;
}
}
A boolean can have two values (true or false). Period. So if you can't change the return type or any variables outside (which would be bad practice anyway), it's not possible to do what you want.
Does adding a parameter to the function violate rule 2? If not, this might be a possible solution:
public static boolean isSimilar(int a, int b, int condition) {
int abs = Math.abs(a - b);
switch (condition) {
case 1:
if (abs == 0) {
return true; // true
}
case 2:
if (abs > 10) {
return true; // false
}
case 3:
if (abs <= 5 && abs != 0) {
return true; // semi-true
}
case 4:
if (abs > 5 && abs <= 10) {
return true; // semi-false
}
default:
return false;
}
}
By calling the function 4 times (using condition = 1, 2, 3 and 4), we can check for the 4 results (only one would return true, other 3 would return false).

Java class won't compile

Im quite the novice when it comes to programming and im trying to translate this PHP algorithm to Java.
function isPrime($n)
{
$i = 2;
if ($n == 2) {
return true;
}
while ($i < $n) {
if ($n % $i == 0) {
return false;
}
$i++;
}
return true;
}
for ($i = 3; $i < 100; $i++) {
if (isPrime($i)) {
echo $i;
}
}
The only thing i've come up with so far is this.
public class Primtal {
public static boolean isPrime(int n)
{
int i = 2;
if (n == 2) {
return true;
}
while (i < n) {
if ( n % i == 0) {
return false;
}
i++;
}
return true;
}
for(int i = 3; i < 1000; i++){
if (isPrime(i)) {
System.out.print(i);
}
}
}
I realize this look really stupid but i really need to get this to work. I think the problem lies mostly with the for loop as im currently getting the error illegal start of type there. Im not really sure how to translate this to Java and i would appreciate any help i can get.
I believe the problem with your code is that you've put a for loop in the middle of class declaration, which is incorrect - it needs to be inside some method. It seems logical in this case to put it in main(), so it's executed when you run your program. Maybe something like this:
public class Primtal
{
public static boolean isPrime(int n)
{
int i = 2;
if(n == 2)
{
return true;
}
while(i < n)
{
if(n % i == 0)
{
return false;
}
i++;
}
return true;
}
public static void main(String[] args)
{
for(int i = 3; i < 1000; i++)
{
if(isPrime(i))
{
System.out.print(i);
}
}
}
}
(Note the addition of public static void main(String[] args) in the second half of the code.)
Oracle has official tutorials on how Java programs need to be structured, and other basics of the language. You can find the one related to the main method here. Or, to start from the beginning, the full tutorial starts here.
you can't write the for loop
for(int i = 3; i < 1000; i++){
if (isPrime(i)) {
System.out.print(i);
}
}
directly inside a class.
i believe what you wish to do is to have a main method, in which you can have the for loop
Your for loop needs to be within a method of some sort,so you can put it in the main method:
public class Primtal {
public static void main(String [] args)
{
for(int i = 3; i < 1000; i++)
{
if (isPrime(i)) {
System.out.print(i);
}
}
public static boolean isPrime(int n)
{
int i = 2;
if (n == 2) {
return true;
}
while (i < n) {
if ( n % i == 0) {
return false;
}
i++;
}
return true;
}
}
The problem is that your for loop isn't in a method. Enclose it in a main method.
public static void main(String[] args) {
// Your for loop here
}
Also, change print to println, or else all the numbers will appear concatenated together on one line.

Resolving PMD Error

I am using PMD for checking Coding Standards
I am confused about the following below point where PMD is showing Error
A method should have only one exit point, and that should be the last statement in the method
Currently inside my Method it is as
public boolean validate()
{
if (length == 4) {
return true;
if (length == 2) {
return false;
else
return false ;
return true ;
}
Is my code is wrong ?? and please tell me how can we chage this in case its wrong ??
Example :
public boolean foo(int i) {
if (i > 0) {
return true; // Multiple exit points
}
return false; // ~ ~ ~
}
public boolean bar(int i) {
boolean bool = false;
if (i > 0) {
bool = true;
}
return bool; // Single exit points
}
See OnlyOneReturn.
See question
Programming preference - use else ifs with multiple return statements?

Categories

Resources