Switch statement involving string and char - java

public class Example {
public static void main (String [] args){
String word = "apple";
switch(word){ // by only changing this value
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("the word starts with a vowel");
break;
default:
System.out.println("the word doesn't start with a vowel");
}
}
}
The error that I'm at is that
char cannot be converted to a String
Am i supposed to be using the charArray() method if that's the case?

It looks like you want the switch case to be for the first letter of the word, not the whole word, so try this:
switch(word.charAt(0)){ // by only changing this value

You should just try and get the first element of the string instead of the whole word. The first element should be a char.
Like word.charAt(0)

Related

java project - Regions

I am working on a project where you enter the abbreviation for a state into a scanner and then the program tells you what region of the U.S. the state is in. I think that the majority of my code is correct, but I have never used switch before.
I have polished my work down to one error, a missing return statement in my first block of code (the switch section). I do not know if any other code is affecting it, so I am just going to post most of it here. Thanks in advance.
import java.util.Scanner;
public class Regions {
public static String getRegion (String stateName){
String region = "";
switch(stateName){
case "ME":
case "VT":
case "NH":
case "MA":
case "CT":
case "RI":
region = "New England";
break;
case "NY":
case "NJ":
case "DE":
case "MD":
case "VA":
case "NC":
case "SC":
region = "Atlantic";
break;
case "GA":
case "FL":
case "MS":
case "AL":
case "LA":
case "TN":
region = "Southeast";
break;
case "PA":
case "OH":
case "MI":
case "IN":
case "IL":
case "WI":
case "MN":
case "KY":
case "WV":
case "IA":
region = "Midwest";
break;
case "ND":
case "SD":
case "KS":
case "NE":
case "MO":
region = "Great Plains";
break;
}
}
public static void main (String[]args){
Scanner s = new Scanner(System.in);
System.out.println("Enter a two-letter state abbreviation:");
String stateName = s.nextLine();
String region = getRegion(stateName);
System.out.print("The state " + stateName);
if (region == "New England"){
System.out.print(" is in the New England region!");
}
else if (region == "Atlantic") {
System.out.print(" is in the Atlantic region!");
}
else if (region == "Southeast") {
System.out.print(" is in the Southeast region!");
}
else if (region == "Midwest") {
System.out.print(" is in the Midwest region!");
}
else if (region == "Great Plains") {
System.out.print(" is in the Great Plains region!");
}
else {
System.out.println ("That's not a state.");
}
}
}`
First Problem : Missing return in getRegion()
Just add
return region;
add the end of that method.
Second Problem : Comparing strings with == instead of equals
In your main replace all
if (region == "..."){
with
if (region.equals("...")){
You eventually need to add a result when to the method is passed an invalid state.
The rest of the code is correct, but you need to return region at the end of the method.
A better code is to return directly instead of using a locale variable region.
public static String getRegion (String stateName){
switch (stateName) {
case "ME":
case "VT":
case "NH":
case "MA":
case "CT":
case "RI":
return "New England";
case "NY":
case "NJ":
case "DE":
case "MD":
case "VA":
case "NC":
case "SC":
return "Atlantic";
case "GA":
case "FL":
case "MS":
case "AL":
case "LA":
case "TN":
return "Southeast";
case "PA":
case "OH":
case "MI":
case "IN":
case "IL":
case "WI":
case "MN":
case "KY":
case "WV":
case "IA":
return "Midwest";
case "ND":
case "SD":
case "KS":
case "NE":
case "MO":
return "Great Plains";
}
throw new IllegalArgumentException("invalid state");
// Or return a special string value
}
As other said there are errors also in the main, but I focused only in the getRegion method that was the question asked. Don't use == operator to compare strings, use the method equals.
== check if two strings are the same object, equals check if two string objects have the same content.
Looks like you just want to put a
return region;
at the end of your getRegion method.
That's it.

Writing a program using Switch Case Statement (with the use of letters ABCD not int)

I have my code written in if/else Statement and it is working but I have a problem in writing it using switch statement as it appears that there are problems in my variables and symbols.
Can you please spot what is wrong and help me correct it?
My source code below.
import java.util.Scanner;
import java.io.*;
public class CourseCodeSWITCH {
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case A: code = "Accounting";
break;
case B: code = "Banking and Finance";
break;
case C: code = "Computer Science";
break;
case D: code = "Dentistry";
break;
case E: code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
}
}
You're using A, B, C, as labels, but that's not how a switch statement works. Let's take a look at just one statement:
switch (code) {
case A: code = "Accounting";
break;
You're switching on code... this means you're going to be examining the contents of the code variable.
Next, you declare a case. In the case above, you're effectively saying
if (code == A)
code = "Accounting";
break;
Now, there's a couple things wrong with that. First of all, A is not defined anywhere, so you're immediately going to run into compile-time errors. You probably wanted to use a String value ("A") instead. Second, you're just reassigning code instead of outputting like you did in your original if-statement.
You probably want a switch that looks closer to the following:
switch(code) {
case "A":
System.out.println("Assignment");
break;
case "B":
System.out.println("Banking and Finance");
break;
// and so forth
}
In Java 7/8 you can define the String to compare code to. In earlier versions you may want to use a char or enum.
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case "A":
code = "Accounting";
break;
case "B":
code = "Banking and Finance";
break;
case "C":
code = "Computer Science";
break;
case "D":
code = "Dentistry";
break;
case "E":
code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
Additionally here is an example from Oracle.

Switch Case Error Validation

Just starting Java so it's probably a simple question but couldn't find any questions like mine so figured I would post one.
I am writing a "main menu" with options 1-8. I figured out how to error handle when someone types a number larger than 8 and less than 1 but I can't figure out how to give them an error message if they type a character or letter...
while(menuChoice != 8)
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
}
Assuming this compiles, what you're asking would be impossible. You're switching on a number, so you can't check if the number is a character. Your code wouldn't compile if that were possible.
You should take the user input as a String and validate the String. If the String has non-numeric values in it, then throw an error. If it doesn't, convert it to a number then execute your switch.
A better design would be to have a validation layer. Once the input is validated, just assume it's valid thereafter.
Pseudocode:
String input = //
if (containsNonNumerics(input))
throw error
inputAsInt = castToInt(input)
if (outOfRange(inputAsInt)
throw error
switch //your current code goes here
First off, having that while loop is not going to give you the functionality that you want. You should look into how to use KeyAdapter in order to be able to receive input events from the keyboad, e.g. a number being pressed, and then you can validate that it is actually a number, and if it is you can then use your switch statement to determine the proper code to execute.
I am guessing that menuChoice is a character. In which case, you can either do a manual check that
if('0' <= mc && mc <= '9') {
// do your regular checks
}
If it is a string then do a
try {
Integer.parseInt(mc)
} catch (NumberFormatException e) { // Not a number. Do your error reporting stuff }
HTH.
Switch statment work only with numeric types (int, byte, char, short). If you try add in switch anything else the compailer wouldent allowe you in general. But if you somehow (cating or other way) want to add in switch statment varible you must befor check it with if statment if the varible is type that you want.
Example:
if(var instanceof String){
System.out.println("Error we don't acceped type string");
}
else{
switch(var){
....
}
}
Use this function before entering into while loop and display the error message.
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
int menuChoice ;
//Now get input from customer in menuChoice
//Your logic goes herr... example menuChoice = ..whateverinput
//After the input is captured then validate
if(menuChoice <1 || menuChoice >8 )
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
else {
System.out.println("Please Enter Valid Entry");
}

Case insensitive matching in Java switch-case statement

I was wondering if there is a way to perform case insensitive match in java switch case statement. the default implementation is case sensitive. Please see the example below.
public class SwitchCaseTest {
/**
* #param args
*/
public static void main(String[] args) {
switch ("UPPER") {
case "upper" :
System.out.println("true");
break;
default:
System.out.println("false");
break;
}
}
}
So above statement returns false as output. And i am trying make it work for case-insensitive match like String.equalsIgnoreCase() would do. I tried to convert both the string literal to lower case and then compare. but was unable to do so.
If you want to do that: just make sure the input data is in all lowercase, and use lowercase cases...
switch ("UPPER".toLowerCase()) {
case "upper" :
....
Localization issues
Also, the ages old issue of localization strikes again, and plagues this thing too... For example, in the Turkish Locale, the uppercase counterpart of i is not I, but İ... And in return, the I is not transformed to i, but a "dotless i": ı. Don't underestimate this, it can be a deadly mistake...
You try making everything uppercase or lowercase
String str = "something".toUpperCase();
switch(str){
case "UPPER":
}
or
String str = "something".toLowerCase();
swtich(str){
case "lower":
}
or even better use enum (note this is only possible from Java 7)
enum YourCases {UPPER1, UPPER2} // cases.
YourCases c = YourCases.UPPER1; // you will probably get this value from somewhere
switch(c){
case YourCases.UPPER1: ....
break;
case YourCases.UPPER2: ....
}
When using a switch statement you must use "break;" for it to exit the statement, so simply use two cases, one without a break.
switch(choice)
{
case 'I':
case 'i':
//Insert a name
System.out.print("Insert a name to add to the list: ");
input.nextLine();
name = input.nextLine();
nameList.insert(name);
System.out.println();
break;
This way, if either "I" or "i" are entered, both cases will have the same outcome.
try
switch ("UPPER".toUpperCase()) {
case "UPPER" :
To avoid having to use the case expression to verify if it is lowercase or uppercase, I recommend that you use the following:
String value = String.valueOf(userChoice).toUpperCase();
This helps to make the conversion of lowercase to uppercase before doing the evaluation in the switch case.

Swtich statement syntax error

I am trying to test if my user submits sensible data , which is later formatted to integer.
Where is the problem with the switch statement? :)
void convert(String str)
{
int i=0;
String x=str.startsWith();
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
int i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
You're switching on x which is a String - unless you're using Java 7, you can't use String in a Switch statement.
I expect the error is actually coming from str.startsWith(), where that method is expecting to take a String (which you're checking what it starts with) and returns a boolean, which you can't switch on either.
UPDATE Correcting your code to do what I think you're trying to do:
void convert(String str)
{
int i = 0;
switch (str.charAt(0)) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
Although the shorter way is just to do the Integer.parseInt call, and handling the NumberFormatException that may occur - then you don't need to do the switch at all.
void convert(String str)
{
try {
int i = Integer.parseInt(str);
System.out.println (i);
} catch (NumberFormatException e) {
System.out.println ("Should start with fixnumber");
}
}
You need to either return i; and convert the method signature from void to int, or otherwise expose the data in i to make it worthwhile.
x is a string and in case you test number.
try:
case "string1"
..
break;
case "string2"
..
break;
etc...
If you're trying to test to see if the string entered is an Integer, then I see no reason to have the switch() in the first place. It would be far better behavior to catch the exception raised when trying to work with the function.
Example:
void convert(String str) { // Heads-up: convert has <package> visibility
int i = 0;
try {
i = Integer.parseInt(str);
System.out.println(i);
} catch (NumberFormatException nfe) {
System.out.println ("Should start with fixnumber");
}
}
Your x is a String. The switch statement is attempting to compare it against integer values. You need something like this:
switch (Integer.parseInt(x))
{
// etc...
EDIT: Actually, now that I see that the string is supposed to be the result of a startsWith call, I'm totally confused about what this code is trying to do.

Categories

Resources