Reputation: 111
So I was trying to create this simple program were a user enters in a month (1-12) and then using switch statements tell them what month it is based upon what they entered. This is my code:
import java.util.Scanner;
class tests{
public static void main(String args[]){
Scanner monthone = new Scanner(System.in);
Double month;
System.out.println("What is the numerical value of the month? 1-12");
System.out.print(monthone.nextLine());
month = monthone.nextDouble();
switch (month){
case 1:
System.out.println("It's January");
break;
case 2: System.out.println("It's Feburary");
break;
case 3:
System.out.println("It's March");
break;
case 4:
System.out.println("It's April");
break;
case 5:
System.out.println("It's May");
break;
case 6:
System.out.println("It's June");
break;
case 7:
System.out.println("It's July");
break;
case 8:
System.out.println("It's August");
break;
case 9:
System.out.println("It's September");
break;
case 10:
System.out.println("It's October");
break;
case 11:
System.out.println("It's November");
break;
case 12:
System.out.println("It's December");
break;
default:
System.out.println("I Don't know what month it is..");
break;
}
}
}
Can anybody provide a solution or help? I tried using a Int for my variable as well but that failed... :s (Please detail answers.. I am here to learn not to be given an answer in a quick reply.)
Upvotes: 1
Views: 79
Reputation: 22715
You've defined month as a Double.
Double month;
However, you can only switch on the following types:
Therefore,
switch (month) {
is syntactically incorrect and will cause a compilation error.
A few other things are not right:
Here's the revised code:
public static void main(String args[]){
Scanner monthone = new Scanner(System.in);
int month;
System.out.println("What is the numerical value of the month? 1-12");
//System.out.print(monthone.nextLine());
month = monthone.nextInt();
switch (month){
case 1:
System.out.println("It's January");
break;
case 2: System.out.println("It's Feburary");
break;
Upvotes: 6
Reputation: 5451
Make your month an int, remove this line: System.out.print(monthone.nextLine());
, and change nextDouble
to nextInt
.
Upvotes: 1
Reputation: 1615
You're also consuming an extra line of input after prompting the user for a value.
System.out.println("What is the numerical value of the month? 1-12");
System.out.print(monthone.nextLine()); // Remove this line
Upvotes: 1