-2

I recently encountered a situation that is somewhat similar to this.

Scanner sc = new Scanner(System.in);
int a = sc.nextInt(), ... , g = sc.nextInt(), x = sc.nextInt(), y = sc.nextInt(), z;
z = x * y;
switch (z)    {
    case a : //print something 
    break;
    .
    .
    .
    case g : //print something 
    break;
    default : //print something 
    break;
}

I encountered an error for all the case labels. I checked through some tutorials and have not got all the answers. I need to know if I can make it work with switch statement since it is a constraint I must use.

Nishanth Rao
  • 11
  • 1
  • 1
  • 4

2 Answers2

1

As pointed out in the comments, you can't use variables as switch cases.

Whenever you find yourself doing the same thing with multiple variables (such as assigning sc.nextInt() to each of the variables a to g), you should consider using a loop instead.

For example:

ArrayList<Integer> inputs = new ArrayList<>();
for (int i = 0; i < 7; i++) {
  inputs.add(sc.nextInt());
}

Then, instead of your switch statement, you can simply iterate over your list.

for (int i : inputs) {
  if (z == i) {
    doSomething();
  }
}
jsheeran
  • 2,912
  • 2
  • 17
  • 32
0

You can simply generate a mapping between your integer and a method. Since all your comment state this will print something, let assume you want a String, so you want to "supply" a String based on an integer.

First, let's define some function :

List<Supplier<String>> functions = new ArrayList<>();
functions.add(() -> "Function #1");
functions.add(() -> "Function #2");
functions.add(() -> "Function #3");
functions.add(() -> "Function #4");

Then, let's create a mapping for each functions:

Map<Integer, Supplier<String>> map = new HashMap<>();
for(Supplier<String> s : functions){
    System.out.print("Define a key for the next function :" );
    map.put(sc.nextInt(), s);
}

And that's it, you have define for each function (not that if you input twice a same key, only the last function will be set to that function, a Collection could be used if you want)

Let's get the function and execute it to get the value :

System.out.println("Execute:");
String value = map.get(sc.nextInt()).get();

This is a short code that doesn't prevent any NullPointerException from happening, this is not the topic of this answer.

PS : don't forget to close the Scanner

sc.close();
AxelH
  • 14,325
  • 2
  • 25
  • 55