How can I get this switch statement to recognize integers? - java

I am trying to write a program that will switch any letter of the alphabet (upper or lower cases) AND number into the Phonetic alphabet. For example, if I enter "A" or "a" my program will give me (change it to) "Alpha". Moreover, if I enter "1" it will return "One". I've successfully managed to work the 'enter-any-letter' aspect of it, but my program does not recognize numbers. I tried putting int but my Scanner does not recognize this. I put a default in my code but still...no prevail. Should I use an if statement instead?
Further note:
This is question is a continuation from this question
Here's what I've got so far:
import java.util.Scanner;
public class PhoneticTranslate {
public static void main(String[] args) {
int number = 0;
char letter;
String phonetic = null;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter or number: ");
letter = kb.next().charAt(0);
switch(Character.toUpperCase(letter))
{
case 'A':
phonetic = "Alpha";
break;
case 'B':
phonetic = "Bravo";
break;
// ... rest of cases for letters
case 'Z':
phonetic = "Zulu";
break;
default:
Scanner x = new Scanner(System.in);
number = kb.nextInt();
switch(number)
{
case '1':
phonetic = "One";
break;
case '2':
phonetic = "Two";
break;
// ... rest of cases for numbers
case '8':
phonetic = "Eight";
break;
case '9':
phonetic = "Nine";
break;
}
}
System.out.println("You Entered " + letter + ". This letter indicates: " + phonetic);
System.out.println("You Entered" + number + ". This number indicates: " + phonetic);
}
}

A giant switch/case clause is a code smell, try this:
Add every key/value pair into a Map, then you retrieve the values with get. No switch/case needed.
String letter;
String phonetic;
Map<String,String> codes = new HashMap<String,String>();
codes.put("A","Alpha");
codes.put("B","Bravo");
codes.put("C","Charlie");
codes.put("D","Delta");
// not showing all "puts" to make it shorter
codes.put("W","Whiskey");
codes.put("X","X-Ray");
codes.put("Y","Yankee");
codes.put("Z","Zulu");
codes.put("0","Zero");
codes.put("1","One");
// not showing all "puts" to make it shorter
codes.put("9","Nine");
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter: ");
letter = kb.next().toUpperCase(); // convert key to uppercase
phonetic = codes.get(letter); // search the value in the map using the key
if (phonetic == null) {
System.out.println("bad code : " + letter);
} else {
System.out.println("Phonetic: " + phonetic);
}

You have written your cases over characters: -
case '1': // This is checking for character '1'
You need to change your cases to take integer values: -
switch(number) {
case 1:
phonetic = "One";
break;
case 2:
... so on

Either don't include the quotes around the number (" case 1: phonetic = "One"" etc), or continue using the char value. I think either one should work.

Your switch statement is checking for the unicode char representation of integers. By this specification, '1' is the character "1" which translates to the integer 49.
Put the int representation of each value in the switch statement:
switch (number) {
case 1:
phonetic = "One";
break;
case 2:
...
}

Try:
Scanner x = new Scanner(System.in);
int number = x.nextInt();
String phonetic = null;
switch(number)
{
case 1:
phonetic = "One";
break;
case 2:
phonetic = "Two";
break;
case 3:
phonetic = "Three";
break;
case 4:
phonetic = "Four";
break;
case 5:
phonetic = "Five";
break;
case 6:
phonetic = "Six";
break;
case 7:
phonetic = "Seven";
break;
case 8:
phonetic = "Eight";
break;
case 9:
phonetic = "Nine";
break;
}

Use the ASCII codes for the numbers instead , that's what chars are anyway. But why do you need to do it? Doesnt your code already work?

Continue your cases into the characters representing integers:
case 'Z':
phonetic = "Zulu";
break;
case '1':
phonetic = "One";
break;
case '2':
// ...
This will work, so long as you only want to handle single-digit numbers.
This matches your problem description, though keeping both a letter and number variable and printing them out separately suggests some additional functionality?

You can try to check if the input value is a digit(int). If not return
while(true){
Scanner x = new Scanner(System.in);
int number=0;
try{
int number = x.nextInt();
}catch(IllegalArgumentException e){
continue;
}
String phonetic = null;
switch(number)
{
case 1:
phonetic = "One";
break;
case 2:
phonetic = "Two";
break;
case 3:
phonetic = "Three";
break;
case 4:
phonetic = "Four";
break;
case 5:
phonetic = "Five";
break;
case 6:
phonetic = "Six";
break;
case 7:
phonetic = "Seven";
break;
case 8:
phonetic = "Eight";
break;
case 9:
phonetic = "Nine";
break;
}
}

Try this one sir
package phone;
import java.util.Scanner;
public class PhoneticTranslate {
/**
* #param args
*/
public static void main(String[] args) {
int number = 0;
char letter;
String phonetic = null;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter or number: ");
letter = kb.next().charAt(0);
switch (Character.toUpperCase(letter)) {
case 'A':
phonetic = "Alpha";
break;
case 'B':
phonetic = "Bravo";
break;
// ... rest of cases for letters
case 'Z':
phonetic = "Zulu";
break;
default:
Scanner x = new Scanner(System.in);
number = kb.nextInt();
switch (number) {
case 1:
phonetic = "One";
break;
case 2:
phonetic = "Two";
break;
// ... rest of cases for numbers
case 8:
phonetic = "Eight";
break;
case 9:
phonetic = "Nine";
break;
}
}
System.out.println("You Entered " + letter + ". This letter indicates: " + phonetic);
System.out.println("You Entered" + number + ". This number indicates: " + phonetic);
}
}

Related

illegal line end in character literal

**About the code: I am just making a simple code using a switch statement. All the switch cases work fine except the double-digit cases. I get an error saying :
year.java:37: error: unclosed character literal
case '10'
year.java:40: error: unclosed character literal
case '11':year.java:43: error: unclosed character literal
case '12'
Code :
import java.util.Scanner;
public class year {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char year;
System.out.println("Enter the number of the month ");
year = input.next().charAt(0);
switch(year){
case '1':
System.out.println("January");
break;
case '2':
System.out.println("Febraury");
break;
case '3':
System.out.println("March");
break;
case '4':
System.out.println("April");
break;
case '5':
System.out.println("May");
break;
case '6':
System.out.println("June ");
break;
case '7':
System.out.println("July");
break;
case '8':
System.out.println("August ");
break;
case '9':
System.out.println("September ");
break;
case '10':
System.out.println("October");
break;
case '11':
System.out.println("November");
break;
case '12'
System.out.println("December");
break;
default:
System.out.println("Invalid");
}
input.close();
}
}
I tried doing a few changes here and there but couldn't understand them and thus could not do so.
Your variable year is a char. A char can only be a single character.
Therefore when you try and do '11' or '12' you run into issues as these "chars" consist of more than one character.
The quick solution here would be to use a String instead of char, using input.next() without the .charAt(0). Then you would need to change your case statements to use double quotes instead of single quotes.
Alternatively, you could do Integer.parseInt(input.next()) and then switch on an int instead, as #Tom has suggested.
First of all, there is a Syntax error in case '12' it should be case '12':
(Also the code indention is bad. Poor indentation make it hard for debugging)
I suggest you convert this code to a String based one. Please check the complete example below.
Char can get one character only and char year; cause a bug, because in input values like 10, 11, 12 it won't work as expected
import java.util.Scanner;
public class year {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String year;
System.out.println("Enter the number of the month ");
year = input.nextLine();
switch(year){
case "1":
System.out.println("January");
break;
case "2":
System.out.println("Febraury");
break;
case "3":
System.out.println("March");
break;
case "4":
System.out.println("April");
break;
case "5":
System.out.println("May");
break;
case "6":
System.out.println("June ");
break;
case "7":
System.out.println("July");
break;
case "8":
System.out.println("August ");
break;
case "9":
System.out.println("September ");
break;
case "10":
System.out.println("October");
break;
case "11":
System.out.println("November");
break;
case "12":
System.out.println("December");
break;
default:
System.out.println("Invalid");
}
input.close();
}
}

Using switch statements for a playing cards program (Java)

I have my program figured out so far, it's just that I'm not understanding these instructions I was given (or at least understanding how to do them).
When I type 10, it prints out "10 of", but when I try to type 10S for 10 of Spades, it only prints out "Spades."
Hopefully, someone here can give me either a solution or point me in the right direction on how to solve my problem:
Use a SWITCH statement to assign the result variable an initial value - the value of the card
Use a second SWITCH statement to concatenate to the result variable the card's suit"
here is the code:
import java.util.*;
public class CardConverter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//will hold string that user will input
String card, face, suit, result;
//getting input from user and telling them correct format
System.out.println("Please enter either the number or face value intial of a card followed by the initial of it's suit (ie. QH for Queen of Hearts)");
card = keyboard.nextLine();
//gets first value
face = card.substring(0);
//sets substring for 10 only
//substring for after all single digit/letter card faces
suit = card.substring(1);
//to print face and word of
switch (face)
{
case "10":
System.out.println("10 of ");
break;
case "2":
System.out.println("2 of ");
break;
case "3":
System.out.println("3 of ");
break;
case "4":
System.out.println("4 of ");
break;
case "5":
System.out.println("5 of ");
break;
case "6":
System.out.println("6 of ");
break;
case "7":
System.out.println("7 of ");
break;
case "8":
System.out.println("8 of ");
break;
case "9":
System.out.println("9 of ");
break;
case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
}
//to print out card suit
switch (suit)
{
case "H":
System.out.println("Hearts");
break;
case "C":
System.out.println("Clubs");
break;
case "S":
System.out.println("Spades");
break;
case "D":
System.out.println("Diamonds");
break;
}
}
}
Your problem starts at card.substring(0);, which equals card because the substring from the start of the String. Maybe you wanted card.charAt(0);? But that is also wrong because "10S" will have three characters, two for the face value.
You'll need to handle a three-character input specially or be smarter about the substring-ing.
You know the suit will always be the last character, so use the length of the string to charAt for that.
int suitIndex = s.length() - 1;
String suit = ""+s.charAt(suitIndex);
String face = s.substring(0,suitIndex);
You can also simplify the cases
case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
default:
System.out.println(face + " of "); // handle all the numbers
break;

How to concatonate two string variables into a result string, after using switch case method to determine new result in java?

So here is a link to another persons question and its my exact assignment.
https://stackoverflow.com/questions/39834840/concatenating-switch-statements-for-playing-cards-assignment
How can I get my result string to display the valueofCard then the suitofCard in this format "value of suit"
Also, how can I shorten up the 2-10 value range within a switch case?
I am aware I have " of " and a couple other lines that make no sense, I just figured I am missing something big anyways.
Thanks for any help, have lots of catching up to do.
System.out.print("Please enter a letter/integer of a playing card (A, J, Q, K, or 2 - 10),\nfollowed by card type (D, H, S, C):");
Scanner kbd = new Scanner(System.in);
String userInput = kbd.nextLine();
String valueofCard = userInput.substring(0, userInput.length() / 2); // gives first half of string
String suitofCard = userInput.substring(userInput.length() / 2); //give last half of string with + 1 if odd
StringBuilder result = new StringBuilder();
switch (valueofCard) {
case "A":
result.append("Ace of ");
break;
case "J":
result.append("Jack of ");
break;
case "Q":
result.append("Queen of ");
break;
case "K":
result.append("King of ");
break;
case "2":
result.append("2 of ");
case "3":
result.append("3 of ");
case "4":
result.append("4 of ");
case "5":
result.append("5 of ");
case "6":
result.append("6 of ");
case "7":
result.append("7 of ");
case "8":
result.append("8 of ");
case "9":
result.append("9 of ");
case "10":
result.append("10 of ");
break;
}
switch (suitofCard) {
case "D":
result.append("Diamonds");
break;
case "H":
result.append("Hearts");
break;
case "S":
result.append("Spades");
break;
case "C":
result.append("Clubs");
break;
}
System.out.println(result.toString());
kbd.close();
}
}
Option 1 - You could use a Stringbuilder to do this.
StringBuilder cardAndSuit = new StringBuilder();
switch (valueofCard) {
case "A":
cardAndSuit.append("Ace of");
.....
switch (suitofCard) {
case "D":
cardAndSuit.append("Diamonds");
break;
...
// Print the final string
System.out.println(cardAndSuit.toString()); // Ace of Diamonds
Option 2 - You could also just create a regular String and append to it.
String cardAndSuit = '';
cardAndSuit += "Ace of";
cardAndSuit += " Diamonds";
System.out.println(cardAndSuit); // Ace of Diamonds
2 is probably easier and more terse. Option 2 will actually be turned into option 1 by the compiler behind the scenes.

Number to Word Conversion in Java

I have this homework assignment for this class I'm retaking, the problem I'm running into is that I'm over-thinking the solution. I have to create a program that converts a four digit number to words.
(Example: 1134 becomes "One One Three Four")
I have a basic code, but it's bulky and ugly. I'm also only allowed to use basic if and switch statements, we have to use a switch statement as well.
Am I over thinking this? I can't figure out how to make this code shorter and I only want to use one switch statement without a while loop. Is it even possible or is this as short as it gets.
Here's my code.
import java.util.Scanner;
public class NumberToWords {
public static void main(String[] args) {
//Set up scanner.
Scanner kb = new Scanner(System.in);
//Ask for a 4 digit integer.
System.out.println("Enter a 4 digit number.");
//Store 4 digit number into a variable
int number = kb.nextInt();
//Seperate number into digits.
int digit4 = number%10;
number = number/10;
int digit3 = number%10;
number = number/10;
int digit2 = number%10;
number = number/10;
int digit1 = number%10;
number = number/10;
//Set up a switch statement to read through the number.
switch (digit1)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit2)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit3)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit4)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
}
}
First, write a method to convert a single digit to a word. Something like,
private static String digitToWord(char ch) {
switch(ch) {
case '0': return "Zero";
case '1': return "One";
case '2': return "Two";
case '3': return "Three";
case '4': return "Four";
case '5': return "Five";
case '6': return "Six";
case '7': return "Seven";
case '8': return "Eight";
case '9': return "Nine";
}
return "Unknown (" + ch + ")";
}
Then you can get the String value of your int. And get the four characters from that String. Something like,
int number = kb.nextInt();
String str = String.format("%04d", number);
StringBuilder sb = new StringBuilder();
sb.append(digitToWord(str.charAt(0)).append(' ');
sb.append(digitToWord(str.charAt(1)).append(' ');
sb.append(digitToWord(str.charAt(2)).append(' ');
sb.append(digitToWord(str.charAt(3));
System.out.println(sb.toString());
Or,
String str = String.format("%04d", kb.nextInt());
System.out.printf("%s %s %s %s%n", digitToWord(str.charAt(0)),
digitToWord(str.charAt(1)), digitToWord(str.charAt(2)),
digitToWord(str.charAt(3)));
this might help
public class NumbersInWords {
public static void main(String[] args) {
String number = "153";
int numLength = number.length();
System.out.println(numLength);
String numberToWord = "";
for (int j = 0; j < numLength; j++) {
switch (number.charAt(j)) {
case '1': {
numberToWord = numberToWord + "one";
break;
}
case '2': {
numberToWord = numberToWord + "two";
break;
}
case '3': {
numberToWord = numberToWord + "three";
break;
}
case '4': {
numberToWord = numberToWord + "four";
break;
}
case '5': {
numberToWord = numberToWord + "five";
break;
}
case '6': {
numberToWord = numberToWord + "six";
break;
}
case '7': {
numberToWord = numberToWord + "seven";
break;
}
case '8': {
numberToWord = numberToWord + "eight";
break;
}
case '9': {
numberToWord = numberToWord + "nine";
break;
}
default: {
numberToWord = numberToWord + "zero";
}
}
}
System.out.println(numberToWord);
}
}
Yeah, you can simply do that operation in a for loop, executed 4 times. The division and mod is consistent at 10. Something like
For i = 0; i < 4; i++
Number/10%10
Condition to check number
Save number in array or print
Copy pasting code and names with numbers should be a red flag to use a loop (or something more is worng).
private static final String[] DIGIT_NAMES = new String[] {"Zero ", "One ", "Two ",
"Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = 0;
do {
// ask for a 4 digit integer
System.out.println("Enter a 4 digit number: ");
try {
number = input.nextInt();
} catch (InputMismatchException ignore) {
System.out.println("Recieved non integer input");
input.next(); // clear bad input
}
} while (number < 1000 || number > 9999);
String result = "";
while (number != 0) {
result = DIGIT_NAMES[number % 10] + result;
number = number / 10;
}
System.out.println(result);
input.close();
}

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

Categories