Decoder java program to turn numbers into letters using a while loop - java

I am creating a decoder program that will essentially turn numbers into specific letters using a while loop but I'm having difficulties figuring out what's wrong with my code and also if there is a simpler way to put it using switch for example. Here is what I have so far:
import java.util.Scanner;
public class Decoder{
public static String decode(String str){
int i = 0;
while(i<str.length()){
if(str.charAt(i)=='1')
return("D");
else if(str.charAt(i)=='2')
return("W");
else if(str.charAt(i)=='3')
return("E");
else if(str.charAt(i)=='4')
return("L");
else if(str.charAt(i)=='5')
return("H");
else if(str.charAt(i)=='6')
return("O");
else if(str.charAt(i)=='7')
return("R");
return("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
public static void main(String[] args){
System.out.println("Enter a number ");
}
}

Sure. Use a constant char array as a lookup table.
At index 0, store 'D'. At index 1, store 'W', etc.
Whenever you encounter a number in the source, subtract '1' to it to get the index in the array for this number, and get the matching letter from the array.
The code is left as an exercise.

Other than the array mentioned by JB Nizet, you could try:
switch statement
a Map<Integer, String> containing the digit/letter pairs

You can use StringBuilder and switch/case like that:
public class Decoder {
public static String decode(String str) {
int i = 0;
StringBuilder decodedString = new StringBuilder();
while (i < str.length()) {
switch (str.charAt(i)) {
case '1':
decodedString.append("D");
break;
case '2':
decodedString.append("W");
break;
case '3':
decodedString.append("E");
break;
case '4':
decodedString.append("L");
break;
case '5':
decodedString.append("H");
break;
case '6':
decodedString.append("O");
break;
case '7':
decodedString.append("R");
break;
default:
return ("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
return decodedString.toString();
}
public static void main(String[] args) {
while (true) {
System.out.println("Enter a number: ");
Scanner input = new Scanner(System.in);
System.out.println(decode(input.next()));
System.out.println();
}
}

Related

infinite loop unable to close loop in Switch Statements

import java.util.Scanner;
class MenuFastFood {
public static void main(String[] args) {
String s;
char order;
Scanner keyboard = new Scanner(System.in);
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);
do {
switch(order) {
case 'A':
System.out.println("CheeseBurger");
System.out.println("Onion Rings");
System.out.println("Soda");
break;
case 'B':
System.out.println("Hot dog");
System.out.println("Fries");
System.out.println("Milk Shake");
break;
default:
System.out.println("error");
return;
case 'X':
System.out.println("EXIT");
break;
}
}while(order != 'X');
}
my program is suppose to pick an item based on the character enter in to keybaord and then loops back if another item is selected. when i run this and pick an item. it loops that item for ever. How do i get that to stop and makes it able for me to select another item?
Move your code for reading input to inside do..while
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);

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

Conflicts between 'for' and 'switch'?

I want to try a little programming that can read user input continuously unless input is 0.
But the problem is whatever I enter (except 0), it always shows "Please choose one" (in default part). If I enter 4, it will show me this phrase twice!
I do not understand why. Is there a conflict between for and switch or something?
Here is code:
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0') {
switch(ch) {
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
}
The problem is char ch = (char)System.in.read();. Java does not support character based input very well, I recommend using a Scanner which fixes your output, however the user now has to press return after each input.
import java.io.IOException;
import java.util.Scanner;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
while (!s.equals("0"))
{
switch(s)
{
case "1":
System.out.println("The If");
break;
case "2":
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
s = in.nextLine();
}
}
}
If you don't want to press return, you can also read the character twice, although I can only speculate why this works is that there is a control character sent over the stream. Edit: I thought it could also be another byte of a UTF-16 character which is not used when typing in ASCII characters but System.in.read() returns integers not bytes.
import java.io.IOException;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0')
{
switch(ch)
{
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
ch = (char)System.in.read();
}
}
}
System.in.read() reads a byte from the InputStream and returns it. When you type 1 or any single digit number and press enter, it reads two characters.
Try tying multiple digit number to see how System.in.read() behaves.
You should use scanner for the console input:
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

On Switch How to use logic operator on case JAVA

i have a problem i dont know what to put on case section, when ever the user input their grades from 0-100 there are output corresponds to their grades failed,good,verygood,excellent.
import java.util.Scanner;
public class ProgTestI {
public static void main (String args[]){
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
switch (grado){
case =<74: /* iwant to put 0 to 74*/
System.out.println("Failed");
case : /* 75-80*/
System.out.println("bellow average");
case : /*81-85*/
System.out.println("average");
case : /*86-90*/
System.out.println("Good");
case : /*91-96*/
System.out.println("VeryGood");
default:
}
}
}
You cannot use switch for ranges, you need to replace this chunk of code with proper if/else blocks.
Switch works only on numeric values, but it works like
if(numericVal == 40)
So writing it for ranges is... waste of code, and not readable.
You need to rewrite it:
if( g <= 74){
...
}else if( g > 74 && g <= 80 ){
...
Your case code is incorrect, you can do as Beri mentioned.
If you want to implement switch statement in your application, then you can do as follows:
public static void main(String[] args) {
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
int checkedCase=0;
if(grado<=74){
checkedCase=1;
}
else if(grado>=75&&grado<=80){
checkedCase=2;
}
else if(grado>=81&&grado<=85){
checkedCase=3;
}
else if(grado>=86&&grado<=90){
checkedCase=4;
}
else if(grado>=91&&grado<=96){
checkedCase=5;
}
switch (checkedCase){
case 1: /* iwant to put 0 to 74*/
System.out.println("Failed");
break;
case 2: /* 75-80*/
System.out.println("bellow average");
break;
case 3: /*81-85*/
System.out.println("average");
break;
case 4: /*86-90*/
System.out.println("Good");
break;
case 5: /*91-96*/
System.out.println("VeryGood");
break;
default: System.out.println("Please enter a value in range 0-96");
break;
}
}

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 '

Categories