Trying to use switch in strings by first coverting string into char and then apply switch but still didnt done it....here is my code..
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
class HappyBirthday {
public static void main(String[] args) throws IOException {
String Month;
char[] Months = Month.toCharArray();
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter your month.");
Month = JOptionPane.showInputDialog("enter month");
String month1 = { "January", "feb"};
char[] month2 = month1.toCharArray();
// String s=month1.equals(Month);
// System.out.print(month2Array[0]);
switch (month2) {
case 0:
System.out.println("kool");
break;
case 1:
System.out.println("not kool");
break;
default:
}
}
}
/**
* if (month1[1].equals(Month)) System.out.println("kool"); else
* if(month1[0].equals(Month)) System.out.println("kooooooooooooool"); else
* System.out.println("Big kooooool");
**/
Have a look at this excellent article on the subject.
Currently, you can not switch on a String. The language specification is clear on what you can switch on:
JLS 14.11 The switch statement
SwitchStatement:
switch ( Expression ) SwitchBlock
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.
Depending on what you want to do, you can switch on each char of a String:
String s = "Coffee, tea, or me?";
int vowelCount = 0;
int punctuationCount = 0;
int otherCount = 0;
for (char letter : s.toUpperCase().toCharArray()) {
switch (letter) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowelCount++;
break;
case ',':
case '.':
case '?':
punctuationCount++;
break;
default:
otherCount++;
}
}
System.out.printf("%d vowels, %d punctuations, %d others",
vowelCount, punctuationCount, otherCount
); // prints "7 vowels, 3 punctuations, 9 others"
Note that switching on strings will be supported in Java 7.
You can't switch on a char[] type. Switch on char[0] and use case 'J': and so on (although - because some months start with the same letter, the algorithm would be sub-optimal)
Related
This question already has answers here:
In a switch statement, why are all the cases being executed?
(8 answers)
Closed last year.
I am working on the game where the columns of the board are represented by the characters but i would like to assign them an index.
I have decided to use the switch statement in that case, however it does produce the wrong result.
With the current code I attach, it gives me 14 as an index, however since the string is 7h, and it takes h as a char, it should give an index of 7. What Could be an issue? Thanks in advance!
public class Check {
public int columnToInt(char c) {
int index=0;
switch(c) {
case 'a':
index=0;
case 'b':
index=1;
case 'c':
index=2;
case 'd':
index=3;
case 'e':
index=4;
case 'f':
index=5;
case 'g':
index=6;
case 'h':
index=7;
case 'i':
index=8;
case 'j':
index=9;
case 'k':
index=10;
case 'l':
index=11;
case 'm':
index=12;
case 'n':
index=13;
case 'o':
index=14;
}
return index;
}
public static void main(String[] args) {
String myStr = "7h";
char c =myStr.charAt(1);
System.out.println("the char at position 1 is "+c);
Check check = new Check();
int result = check.columnToInt(c);
System.out.println(result);
}
}
Java switch statements can be a bit annoying to use. You need to use break or all the cases after the expected one will be executed as well.
switch(c) {
case 'a':
index=0;
break;
Alternatively you can use a return.
switch(c) {
case 'a':
return 0;
You must add the break keyword for each case.
For example:
case 'a':
index=0;
break;
otherwise next assignments are applied.
why cant i convert String to char & use in Switch Statement & if i left it as string the switch statement wont accept it either telling me it needs to be int or byte or short !!
public class Main {
public static void main(String[] args) {
String var1=getInput("enter first variable");
String var2=getInput("enter second variable");
String var3=getInput("enter opertaor");
char c = var3.charAt(0);
double d1=Double.parseDouble(var1);
double d2=Double.parseDouble(var2);
switch(c){
case "+"://squiggly line appears & the bubble help says incompatible types
System.out.println(d1+d2);
break;
case "-"://squiggly line appears & the bubble help says incompatible
System.out.println(d1-d2);
break;
case "*"://squiggly line appears & the bubble help says incompatible
System.out.println(d1*d2);
break;
case "/"://squiggly line appears & the bubble help says incompatible
System.out.println(d1/d2);
break;
default:
System.out.println("Unrecognized operation");
break;
}
}
static String getInput(String prompt){
System.out.println("prompt");
Scanner sc=new Scanner(System.in);
return sc.nextLine();
}
}
You can use a String in case expressions, no need for a char. Change c like
String c = var3.substring(0, 1);
and your code would work. Alternatively, modify your case statements to use char. Like,
switch (c) {
case '+':
System.out.println(d1 + d2);
break;
case '-':
System.out.println(d1 - d2);
break;
case '*':
System.out.println(d1 * d2);
break;
case '/':
System.out.println(d1 / d2);
break;
default:
System.out.println("Unrecognized operation");
break;
}
You can use a char literal instead:
switch(c){
case '+':
System.out.println(d1+d2);
break;
...
The types are different so you can't directly compare them. They happen to be convertible in this particular case, but that's not true in general, so the compiler can't allow that.
Try out below code and it will execute
public static void main(String[] args) {
String var1 = getInput("enter first variable");
String var2 = getInput("enter second variable");
String var3 = getInput("enter opertaor");
char c = var3.charAt(0);
double d1 = Double.parseDouble(var1);
double d2 = Double.parseDouble(var2);
switch (c) {
case '+':
System.out.println(d1 + d2);
break;
case '-':
System.out.println(d1 - d2);
break;
case '*':
System.out.println(d1 * d2);
break;
case '/':
System.out.println(d1 / d2);
break;
default:
System.out.println("Unrecognized operation");
break;
}
}
static String getInput(String prompt) {
System.out.println("prompt");
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
Change case '+': instead of comparing String case "+": Also Check your Java version, From JDK v1.7 will allow you to use Strings in switch statement as what you did in your code snippet. Let me know if you are looking for another solution
You cant parse a String into a char because a String is to big to fit.
Think of it like a String consist of multiple chars, so its just like a char array in one piece.
Im trying to replace each letter with a digit using the international standard letter/number mapping. I got my output to run correctly however, how do get the dashes in the phone number to appear automatically in the output? For example, if I enter 1800Flowers it prints out as 18003569377. How do I get it to print out as 1-800-3569377 without using regular expressions?
import java.util.Scanner;
public class PhoneKeypad {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//while loop keeps the program running until the user enters quit
while (true) {
System.out.println("\nEnter a phone number or quit to exit:");
String phoneNumber = input.next();
if (phoneNumber.equalsIgnoreCase("quit")) {
System.out.print("\nProgrammed by me");
return;
}
//checks if the phone number entered is at least 8 digits
if (phoneNumber.length() < 8) {
System.out.println("Invalid Phone Number");
} else {
System.out.println(getNumber(phoneNumber));
}
}
}
//method converts all letters in the phone number to digits
public static String getNumber(String phoneNumber) {
int keypadNum = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
char letter = phoneNumber.charAt(i);
if (Character.isAlphabetic(letter)) {
letter = Character.toUpperCase(letter);
switch (letter) {
case 'A':
case 'B':
case 'C':
keypadNum = 2;
break;
case 'D':
case 'E':
case 'F':
keypadNum = 3;
break;
case 'G':
case 'H':
case 'I':
keypadNum = 4;
break;
case 'J':
case 'K':
case 'L':
keypadNum = 5;
break;
case 'M':
case 'N':
case 'O':
keypadNum = 6;
break;
case 'P':
case 'Q':
case 'R':
case 'S':
keypadNum = 7;
break;
case 'T':
case 'U':
case 'V':
keypadNum = 8;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
keypadNum = 9;
break;
default:
System.out.println("Invalid phone number");
}
phoneNumber = phoneNumber.substring(0, i) + keypadNum + phoneNumber.substring(i + 1);
}
}
return phoneNumber;
}
}
Expected Output:
You could use a regular expression with String.replaceAll. Remove the leading one, group the first three digits, the second three digits and the final group of digits. Something like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return phoneNumber.replaceAll("(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
or
public static String formatNumber(String phoneNumber) {
return phoneNumber.replaceAll("1(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
And then call it like
System.out.println(formatNumber(getNumber(phoneNumber)));
I ran it with 1800flowers and got (as expected)
1-800-356-9377
or without regular expressions like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return "1-".concat(phoneNumber.substring(0, 3)) //
.concat("-").concat(phoneNumber.substring(3, 6)) //
.concat("-").concat(phoneNumber.substring(6));
}
Before calling formatNumber, you can remove the dashes to normalize it with something like
public static String removeDashes(String phoneNumber) {
StringBuilder sb = new StringBuilder();
for (char ch : phoneNumber.toCharArray()) {
if (ch != '-') {
sb.append(ch);
}
}
return sb.toString();
}
Then
System.out.println(formatNumber(removeDashes(getNumber(phoneNumber))));
when i try to print out the result with switch i can't get any result
so i thought to convert char to integer so the switch statement gona work but isn't so any ideas about how to find solution
echar guestGuess = input.next().charAt(0);
int x = (int)guestGuess;
switch(x){
case '1':
System.out.println(answer.isfirstGuessRight(guestGuess) + "\n");
break;
case '2:
'System.out.println("We are kontrol your answer" + answer.issecandGuessRight(guestGuess));
There's not problem in Java to use char for switch.
You don't have to cast to int for that.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter something, and I'll take the first char only");
char c = scan.next().trim().charAt(0);
switch (c) {
case '1':
System.out.println("1 for sure");
break;
case '2':
System.out.println("I think it's 2");
break;
default:
System.out.println("I don't know");
}
}
Basically I need to take a letter A-Z and convert it to Leek(a combo of sign,#,letter that look like the A-Z characters. I'm only allow to use switch statements (switch,case,breaks) also I have to use the .next().charAt(0) method.
When I try to compile my program it comes up with multiple error all reading "can not find symbol" pointing at the a-z character I used in the case statement.
import java.util.Scanner;
public class dlin_Leet
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
char character;//input by user
String Leet;
System.out.print("Enter character to convert:");
String Leet = input.next();
char character = Leet.charAt(0);
switch (character)
{
case a: Leet = "4";
break;
case b: Leet = "I3";
break;
case c: Leet = "[";
break;
case d: Leet = ")";
break;
case e: Leet = "3";
break;
case f: Leet = "|=";
break;
case g: Leet = "&";
break;
case h: Leet = "#";
break;
case i: Leet = "1";
break;
case j: Leet = "J";
break;
case k: Leet = "|<";
break;
case l: Leet = "1";
}
System.out.println(Leet);
}
}
The character constants must be in into apostraphs:
case 'a': instead of case a:
Fix your code and I hope this is the only syntax error you have.
Also
- You are declaring variable "Leet" and "character" twice in the same block( Duplicate local variable)
case statement using char (which means single quote), it should be something like
switch (character)
{
case 'a': Leet = "4";
break;
case 'b': Leet = "I3";
break;
.........
}
your case should be a char like case 'a'
switch(character)
{
case 'a':
//do your stuff
}
and also you are declaring leet(String variable twice). just declare it one and use the same variable when you get input from the scanner
Using strings in switch case can only be used if you using JDK7 and even then you will have to have the values in quotes.
Like
case "a":