Ciro Ciro - 2 months ago 7
Java Question

'void' type not allowed here and "not a statement"

I've just started trying to develop something with Java, so I wanted to make a little calculator. The problem's that it executes well but still says there's a problem in the 33th line of code.. can you help me? The error message is : 'void' type not allowed here - and there's another one that says "not a statement".. I'm using NetBeans 8.1, can you help me? Here's the code :)

package javaapplication1;

import java.util.Scanner;

public static void main(String[] args) {
System.out.println("Inserire un numero: ");
Scanner a = new Scanner(System.in);
int a1 = a.nextInt();
System.out.println("Inserire il segno d'operazione: ");
Scanner segno = new Scanner(System.in);
String s1 = segno.nextLine();
System.out.println("Inserire un secondo numero: ");
Scanner b = new Scanner(System.in);
int b1 = b.nextInt();
switch(s1) {
case "+": System.out.println("Il risultato è: "+ (a1+b1));
case "-": System.out.println("Il risultato è: "+ (a1-b1));
case "*": case "x": System.out.println("Il risultato è: "+ (a1*b1));
case ":": case "/": System.out.println("Il risultato è: ")+ (a1/b1);
default: System.out.println("Errore: segno non valido.");
}
}
}


Thank you so much :)

Answer

You only defined the method name, but not the class name. A java class is build like:

public class <Classname> {
    void v1() {...}
    void v1() {...}
    void v1() {...}     
}

Also you have a bug with the switch statement.

String s1 = "+"

switch (s1) {
    case "+":
        // This will execute
    case "-":
        // This will execute too
}

So you need to add a break at the end of the code of one case:

String s1 = "+"

switch (s1) {
    case "+":
        // This will execute
        break;
    case "-":
        // This won't execute
        break;
}