I'm having some trouble with my switch statement - java

Ok so I've been programming for a short time and I've already started making pretty nice programs. But when it comes to switches it's always luck when they actually work. I wrote this switch statement:
String answer1 = in.nextLine();
switch (answer1)
{
case 1:
System.out.println("...");
break;
case 2:
System.out.println("...");
break;
case 3:
System.out.println("...");
break;
}
And the switch labels next to the cases all said 'error cannot convert from int to string' could someone please help. Thanks
Noob programmer~ Chase

You are trying to switch on a String, while the cases are ints. You need to parse the string before passing it to switch:
String answer1 = in.nextLine();
switch (Integer.parseInt(answer1)) {
...
}

Strings in switch are supported only from Java 7.
http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html
If you are using Java 7 and above then
switch (answer1)
{
case "1":
System.out.println("...");
break;
case "2":
System.out.println("...");
break;
case "3":
System.out.println("...");
break;
else you have to convert it to int as shown in the answer by #dasblinkenlight

You might need to verify the version of Java you're using. This was not possible on older versions of Java.
See: Why can't I switch on a String?
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
That is, if you intend to switch on String. See the below answer (#dasblinkenlight) if you do indeed expect an integer (You need to parse it).

Related

New to Java trying to make a switch

I am trying to make a switch that will step through the code like in Javascript by adding "jedi++" at the end but it won't let me do that any suggestions on how I can accomplish that? Here is a snippet of the code.
switch(jedi){
case 1:
while(!input.equalsIgnoreCase("guardian") && !input.equalsIgnoreCase("sentinel") && !input.equalsIgnoreCase("consular")){
System.out.println("Please enter the path followed by this Jedi.");
System.out.println("(Guardian, Sentinel or Consular)");
}
registrant.setPath(input);
break;
case 2:
while(!input.equalsIgnoreCase("master") && !input.equalsIgnoreCase("knight") && !input.equalsIgnoreCase("padawan")
&& !input.equalsIgnoreCase("youngling")){
System.out.println("Please enter the Jedi's Rank.");
System.out.println("(Master, Knight, Padawan, Youngling)");
input = keyboard.nextLine();
}
registrant.setRank(input);
break;
jedi++;
}
Do you want to jedi++ in all the cases or just in case 2?
If it's just for case 2, you could do
case 2:
....
jedi++;
break;
case 3:
....
if it's for all the cases, you could do jedi++ after the switch block.
Statements can exist only within the case. since jedi++ is not part of case, its throwing error. Putting the increment statement under required case statement will solve the issue.

switch depending on value inside function [duplicate]

void menu() {
print();
Scanner input = new Scanner( System.in );
while(true) {
String s = input.next();
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "[A-Z]{1}[a-z]{2}\\d{1,}": filminfo( s ); break;
case "Jur1": filminfo(s); break; //For debugging - this worked fine
case "q": ; return;
}
}
}
It seems like either my regex is off or that I am not using it right in the case-statement. What I want is a string that: Begins with exactly one uppercase letter and is followed by exactly two lowercase letters, which are followed by at least one digit.
I've checked out the regex API and tried the three variants (greedy, reluctant and possessive quantifiers) without knowing their proper use. Also checked the methods for String without finding a method that seemed pertinent to my needs.
You can't use a regex as a switch case. (Think about it: how would Java know whether you wanted to match the string "[A-Z]{1}[a-z]{2}\\d{1,}" or the regex?)
What you could do, in this case, is try to match the regex in your default case.
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "q": return;
default:
if (s.matches("[A-Z]{1}[a-z]{2}\\d{1,}")) {
filminfo( s );
}
break;
}
(BTW, this will only work with Java 7 and later. There's no switching on strings prior to that.)
I don't think you can use regex in switch cases.
The String in the switch expression is compared with the expressions
associated with each case label as if the String.equals method were
being used.
See http://download.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html for more info.

How to use String[] inputs in switch case in Android?

How to use the inputs of string array in switch case?
String[] mon=new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};
switch (mon)
{
case "January":
m=1;
break;
case "February":
m=1;
break;
}
Java (before version 7) does not support String in switch case. But you can achieve the desired result by using an enum.
private enum Mon {
January,February,March,April,May,June,July,August,September,October,November,December
};
String value; // assume input
Mon mon = Mon.valueOf(value); // surround with try/catch
switch(mon) {
case January:
m=1;
break;
case February:
m2;
break;
// etc...
}
Please see here for more info
Since JDK 7 you can have a String in a switch. but not a String array....
here's an example
in your code, you're trying to put the whole array into the switch.
try this:
String[] mon=new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};
String thisMonth = mon[5];
switch (thisMonth)
{
case "January":
m=1;
break;
case "February":
m=2;
break;
...
case "June":
m=6;
break;
}
You cannot use an array in a switch statement (before Java 7). If you are using Java 6 for Android development, you cannot switch on Strings either. Its better you use an enumeration for the months, then switch on the enumeration.

if else or switch case [duplicate]

This question already has answers here:
Is "else if" faster than "switch() case"? [duplicate]
(14 answers)
Closed 9 years ago.
I need to check a small piece of logic and would highly appreciate if someone can give me some valuable input.
I have two ways of checking my logic and want to know which is more efficient.
1st way:
if(url.equalsIgnoreCase("1")){
url = "aaa";
}
else if(url.equalsIgnoreCase("2")){
url = "bbb";
}
else if(url.equalsIgnoreCase("3")){
url = "ccc";
}
else if(url.equalsIgnoreCase("4")){
url = "ddd";
}
else if(url.equalsIgnoreCase("5")){
url = "eee";
}
else if(url.equalsIgnoreCase("6")){
url = "fff";
}
2nd Way:
int temp = Integer.parseInt(url);
switch (temp) {
case 1:
url = "aaa";
break;
case 2:
url = "bbb";
break;
case 3:
url = "ccc";
break;
case 4:
url = "ddd";
break;
case 5:
url = "eee";
break;
case 6:
url = "fff";
break;
}
Please let me know which is more efficient. Is it bad to use Integer.parseInt(string)?
If your values really are 1-6, the clearest and most efficient way is using an array :
String[] URLS = {...};
url = URLS[Integer.parseInt(url) - 1];
Please let me know which is more efficient.
a switch statement is more efficient is your case
Is it bad to use Integer.parseInt(string)?
No. it's fine. but when you're using java7 you can use String-constants values in your switch cases but not on Android.
Asside from the efficiency: switch looks cleaner in most cases.
In terms of efficiency check this: Case vs If Else If: Which is more efficient?, but Way 2 looks to be a more clean and readable code.
As a general rule, the switch statement produces more efficient bytecode. With Java 7, switch statements with String was introduced, so you don't need to cast it.
In this case, switch is more efficient.
In fact, If you are using Java7, you may directly use string case rather than using Integer.parseInt().
It is not bad using parseInt but it will throw an exception if the string is not an integer.
otherwise, and I think you can see this for yourself, the switch/case is much more readible.
if your if construct would have a final else catching all other cases (including non numeric strings)
then you can do, assuming your ints are always positive
int temp = -1;
try {
temp = Integer.parseInt(str);
} catch (NumberFormatException ex) {
// ignore exception and use -1 as original value for default case
}
Readability and debugability (is that even a word?) are rather subjective but some people (including me) find the switch statement to be more clear. However, in many cases a compiler has a better chance of generating faster code using a switch compared to the if else construct.
The switch statement is faster for the following two reasons.
The switch statement is generally faster than if-else-if construct because the control is directly transferred to the respective case. While in the cases of if-else-if, the all the checks are going to be performed to reach the first matching condition. For example, if you assign temp = 6 the switch statement will execute the respective block directly. The if-else-if construct will iterate through all the conditions.
Calling the equalsIgnoreCase() is more costly than performing the equality check that happens at the background of the case matching.
for such a long list is a switch statement definitely the better choice. The longer the junction is if the better cut off a switch in comparison
Efficiency depends on the matching condition in both cases.Please conform your answer here.
I think an alternative approach would be to use a pre initialized map. It should have the (string)numbers as the key and the url results as value. Then you can simply do
url = map.get(Integer.parseInt(url));
This is probably even a much cleaner version then the long switch statement.
The switch has more features than the if else, because you can fall through cases.
See for details: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
will output
Number of Days = 29
So it also depends on your implementation requirements which one you use.

Using regex for switch-statement in Java

void menu() {
print();
Scanner input = new Scanner( System.in );
while(true) {
String s = input.next();
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "[A-Z]{1}[a-z]{2}\\d{1,}": filminfo( s ); break;
case "Jur1": filminfo(s); break; //For debugging - this worked fine
case "q": ; return;
}
}
}
It seems like either my regex is off or that I am not using it right in the case-statement. What I want is a string that: Begins with exactly one uppercase letter and is followed by exactly two lowercase letters, which are followed by at least one digit.
I've checked out the regex API and tried the three variants (greedy, reluctant and possessive quantifiers) without knowing their proper use. Also checked the methods for String without finding a method that seemed pertinent to my needs.
You can't use a regex as a switch case. (Think about it: how would Java know whether you wanted to match the string "[A-Z]{1}[a-z]{2}\\d{1,}" or the regex?)
What you could do, in this case, is try to match the regex in your default case.
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "q": return;
default:
if (s.matches("[A-Z]{1}[a-z]{2}\\d{1,}")) {
filminfo( s );
}
break;
}
(BTW, this will only work with Java 7 and later. There's no switching on strings prior to that.)
I don't think you can use regex in switch cases.
The String in the switch expression is compared with the expressions
associated with each case label as if the String.equals method were
being used.
See http://download.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html for more info.

Categories