why cant i convert String to char & use in Switch Statement directly? - java

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.

Related

Java Calculator char thread

This is my void main in my code. When I compile the code it shows no errors, But when I type any random letters then it shows the following thread.
Output:
Please enter the equation :
2323.10ffxcv
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at Calculator.main(calculator.java:31)
[This is the output in CMD.][1]
Code:
Calculator calc = new Calculator();
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter the equation : ");
double a = numbers.nextDouble();
char sign = numbers.next().charAt(0);
double b = numbers.nextDouble();
switch (sign) {
case '+':
calc.add(a, b);
break;
case '-':
calc.sub(a, b);
break;
case '*':
calc.multiply(a, b);
break;
case '/':
calc.divide(a, b);
break;
default:
System.out.println("Sorry I ( The program ) did not understand");
while (sign != '+' || sign != '-' || sign != '*' || sign != '/') {
switch (sign) {
case '+':
calc.add(a, b);
break;
case '-':
calc.sub(a, b);
break;
case '*':
calc.multiply(a, b);
break;
case '/':
calc.divide(a, b);
break;
default:
System.out.println("Sorry I ( The program ) did not understand");
break;
}
}
break;
}
Please help!
The Scanner class won't tokenize your input the way you seem to assume. That is, numbers.nextDouble() doesn't read up until the end of the first bit of data that looks like a Double. It reads the entire line, and attempts to parse it as a Double. You get an InputMismatchException because the input (2323.10ffxcv) doesn't match the expected data type (Double).
You need to find a way to either tokenize the string yourself, or simply enter each value on its own line. Even so, the last part of your input (ffxcv) is still going to break things, because it can't be parsed as a Double.

switch with character, how to convert character to work with switch ?

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");
}
}

Switch statement in Java

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":

How do I use a char as the case in a switch-case?

How do I use a character in a switch-case? I will be getting the first letter of whatever the user inputs.
import javax.swing.*;
public class SwitchCase {
public static void main (String[] args) {
String hello = "";
hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello;
switch(hi) {
case 'a': System.out.println("a");
}
}
}
public class SwitCase {
public static void main(String[] args) {
String hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello.charAt(0); // get the first char.
switch(hi) {
case 'a': System.out.println("a");
}
}
}
charAt gets a character from a string, and you can switch on them since char is an integer type.
So to switch on the first char in the String hello,
switch (hello.charAt(0)) {
case 'a': ... break;
}
You should be aware though that Java chars do not correspond one-to-one with code-points. See codePointAt for a way to reliably get a single Unicode codepoints.
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
Like that. Except char hi=hello; should be char hi=hello.charAt(0). (Don't forget your break; statements).
Using a char when the variable is a string won't work. Using
switch (hello.charAt(0))
you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside
case 'a '

using switch in strings

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)

Categories