user2570147
user2570147

Reputation:

"boolean"s and "switch" statements (error)

I hope you are all doing well. This is my first time on Stack Overflow, so I apologize in advance for any mistakes that I may make. So, let's get to it!

import java.math.BigInteger;

public class Classes {

  static int i;        // "i" is initialized
  static int x = 200;  // FYI, x is the upper limit for primes to be found (ex, in this case, 0 - 200)

  public static void main(String[] args) {
    for (i = 0; i < x;) {                      // "i" is assigned the value of 0 
      BigInteger one = BigInteger.valueOf(i); // The following lines find the prime(s)
      one = one.nextProbablePrime();          // Order by which primes are found - int > BigInteger > int
      i = one.intValue();                    //'i" is re-assigned the a value
    
      if (i >= x) {     
        System.exit(i);     
      }
    
      switch (i) {
        case i < 100:      // ERROR HERE, "Type mismatch: cannot convert from boolean to int"
          hex();
          break;
        case i > 100:      // ERROR HERE, "Type mismatch: cannot convert from boolean to int"
          baseTen();
          break;
      }
    }
  }

  static void hex() { //Probably unimportant to solving the problem, but this is used to convert to hex / print
    String bla = Integer.toHexString(i);
    System.out.println(bla);
  }

  static void baseTen(){  //Probably unimportant to solving the problem, but this is used print
    System.out.println(i);
  }
}

I wrote the above code as a practice piece while learning Java and have been using it since to practice and play around with Java. The program was made to find prime numbers and has been working for some time now.

Ever since I decided to try out switch statements, I have been having problems. When I go to run the code, the Eclipse IDE says "Type mismatch: cannot convert from boolean to int" and because of this my program refuses to run.

I have commented my code with the points at which I cast types and nowhere do I cast "i" into the type "boolean". If you have any idea as to why this problem occurs, please let me know. If you require any additional info, please do ask! Thank You!

Upvotes: 0

Views: 5226

Answers (5)

user85421
user85421

Reputation: 29700

This kind of can be done using Pattern Matching with a Guard, released in Java 21 (JEP 441.)

switch ((Integer) i) {
    case Integer j when j < 100 -> hex();
    case Integer j when j > 100 -> baseTen();
    default -> somethingElse();
}

But "can be" does not mean it should be - I would hardly recommend doing that in production code, unless for some special use case. A simple if-else will do the job and not be harder to understand.


Another alternative, if using a switch is required:

private static final int NEGATIVE = -1;
private static final int POSITIVE = +1;
// . . . 
switch (Integer.signum(i-100)) { 
    case NEGATIVE -> hex(); 
    case POSITIVE -> baseTen();
    default -> somethingElse();
}

or:

private static final int NEGATIVE = -1;
private static final int POSITIVE = +1;
// . . . 
switch (Integer.signum(i-100)) { 
    case NEGATIVE: hex(); break;
    case POSITIVE: baseTen(); break;
    default: somethingElse(); break;
}

The signum() method is documented as:

Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)

Upvotes: 1

nanofarad
nanofarad

Reputation: 41281

switch(i){

can only switch for single values of i for each case.

Use the following instead:

if(i < 100){
    hex();
}
if(i > 100){
    baseTen();
}

I'd also handle the i==100 case as well. This is left as a simple exercise to the reader.

You can only switch for an Enum or if you have distinct int values that you only care about single value cases, not ranges.

Upvotes: 5

OldProgrammer
OldProgrammer

Reputation: 12169

Welcome to SO. If you read the Java documentation, it states:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.

See reference here: Java Switch

Upvotes: -1

Timo Geusch
Timo Geusch

Reputation: 24351

switch statements in Java and most other languages work on constants, not conditions. So, you can write

switch (i)
{
  case 1:
    do_something();
    break;
  case 2:
    do_something_else();
    break;
  default:
    third_option();
}

However, your conditions involve comparisons and not conditions, so in Java they require an if statement:

if (i < 100)
  hex();
else if (i > 100)
  baseTen();

You can find an exhaustive description of the switch statement here.

Upvotes: 0

Jeff Bowman
Jeff Bowman

Reputation: 95704

switch is an element designed to test one variable against a wide variety of possibilities, like this:

switch (a) {
case 1:
  // this runs if a == 1
  break;
case 2:
  // this runs if a == 2
  // NOTE the lack of break
case 3:
  // this runs if a == 2 or a == 3
  break;
default:
  // this runs if a is none of the above
}

Note here that the type in the switch clause (a) should match the type in the case clauses (1). The case clauses can't be arbitrary booleans.

Of course, if you want to specify exactly what the conditions are, you can use an "if/else" block, like this:

if (a == 1) {
  //...
} else if (a == 2) {
  //...
} else if (a == 3) {
  //...
} else {
  // runs if none of the above were true
}

That latter example is closer to what you want; instead of testing each with an ==, each boolean expression after the if is evaluated directly. Yours would look more like this:

if (i < 100) {
    hex();
} else if (i > 100) {
    baseTen();
}

Of course, they could stay two separate clauses, but because they're mutually exclusive it makes sense to still use else. You also haven't accounted for the case where i == 100, which may warrant changing < to <= or > to >=.

Upvotes: 1

Related Questions