How to convert If statement to switch statement? - java

how can I convert this if statement to switch statement by considering that I am using two variables here and I tried to solve it but not working
int child;
char gender;
int temp;
child=console.nextInt();
gender=console.next().charat(0);
if(gender=='m' && children>=4)
temp =1;
else if(gender=='m' && children<4)
temp =2;
else if(gender=='f' && children<4)
temp =3;
else
temp=4;
}
this is my code
int children;
double temp;
char gender;
children=console.nextInt();
switch(children , gender )
{
case < 4, 'm':
temp=1;
break;
default : salary=600;
}

You should start by having a look at The switch Statement
The switch statement is basically evaluating a single condition per case. You can use drop through conditions, but that's a lot of additional code.
For example, something like...
switch (gender) {
case 'm':
temp = 0;
if (children >= 4) {
temp += 1;
} else {
temp += 2;
}
break;
case 'f':
temp = 2;
if (children >= 4) {
temp += 2;
} else {
temp += 1;
}
break;
}
would generate the same results as your if statements
If you preferred to use pure switch statements, you could do something like...
switch (gender) {
case 'm':
temp = 0;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 2;
break;
default:
temp += 1;
}
break;
case 'f':
temp = 2;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 1;
break;
default:
temp += 2;
}
break;
}
Java's switch statement doesn't support ranges :(

switch (gender) {
case 'm':
temp = (children >= 4)? 1:2;
break;
case 'f':
temp = (children >= 4)? 4:3;
break;
default:
temp = 4;
break;
}

Related

How do I convert number to a letter in Java? [duplicate]

This question already has answers here:
Switch statement with string wrong output
(2 answers)
Closed 2 years ago.
I want to make a program to convert number to letter, from 0-9 to ABCDEFGHIK.
For example:
with n = 10 the output would be BA as 0 is A is 0 and B is 1.
Here is my code:
String convertNumber(long n) {
String result="";
String strN = Long.toString(n);
for (int i=0; i < strN.length();i++){
char ch = strN.charAt(i);
switch(ch){
case '0':
result = "A";
case '1':
result = "B";
case '2':
result = "C";
case '3':
result = "D";
case '4':
result = "E";
case '5':
result = "F";
case '6':
result = "G";
case '7':
result = "H";
case '8':
result = "I";
case '9':
result = "K";
}
}
return result;
}
However, the results returns only K. Where did I do wrong? Thank you!
There are three mistakes in your program:
Not using break with the case and therefore every case will fall to the last case.
Using = instead of +=
Using the loop in reverse order than the required order. It should be for (int i = strN.length() - 1; i >= 0; i--) instead of for (int i=0; i < strN.length();i++)
Given below is your corrected program:
public class Main {
public static void main(String[] args) {
System.out.println(convertNumber(10));
}
static String convertNumber(long n) {
String result = "";
String strN = Long.toString(n);
for (int i = strN.length() - 1; i >= 0; i--) {
char ch = strN.charAt(i);
switch (ch) {
case '0':
result += "A";
break;
case '1':
result += "B";
break;
case '2':
result += "C";
break;
case '3':
result += "D";
break;
case '4':
result += "E";
break;
case '5':
result += "F";
break;
case '6':
result += "G";
break;
case '7':
result += "H";
break;
case '8':
result = "I";
break;
case '9':
result = "K";
}
}
return result;
}
}
Output:
AB
You can use this one:
static String convertNumber(int n) {
int reminder;
char[] arr = "ABCDEFGHIK".toCharArray();
int len = arr.length;
StringBuilder builder = new StringBuilder();
while (n != 0) {
reminder = (int) n % 10;
n /= 10;
builder.append(arr[(reminder % len)]);
}
return builder.toString();
}
, main
static public void main(String[] args) {
System.out.println(convertNumber(65));
System.out.println(convertNumber(78));
System.out.println(convertNumber(99));
System.out.println(convertNumber(901));
}
, output
FG
IH
KK
BAK
You forgot the break. add break; in every case, like this:
case '0':
result = "A";
break;
case '1':
result = "B";
break;

Calculate Points from Letters in a Switch Case

I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pointsproblem;
/**
*
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PointsProblem {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
//create new object//
PointsProblem task1 = new PointsProblem();
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + input);
System.exit(0);
}
else {
System.out.println("Successfully opened file: " + input + ".");
}
//read all the lines in the file//
{
while (input.hasNext()) {
String word = input.nextLine();
System.out.println(word);
System.out.println("'" + input + "' is worth " + point + " points");
int point = "";
switch(point) {
case 'a': = "1":
case 'e': = "1";
case 'i': = "1";
case 'l': = "1";
case 'n': = "1";
case 'o': = "1";
case 'r': = "1";
case 's': = "1";
case 't': = "1";
case 'u': = "1";
case 'g': = "2";
case 'g': = "2";
case 'b': = "3";
case 'm': = "3";
case 'c': = "3";
case 'p': = "3";
case 'f': = "4";
case 'h': = "4";
case 'v': = "4";
case 'w': = "4";
case 'y': = "4";
case 'k': = "5";
case 'j': = "8";
case 'x': = "8";
case 'q': = "10";
case 'z': = "10";
return score = point + "";
}//end switch
}//end point calculation loop
public int getScore() {
return score;
}
//public boolean containsLetter(Character letter) {
//return points.contains(letter);//
}
I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.
Looks like a Map<Character, Integer> would fit:
public class PointsProblem {
final Map<Character, Integer> pointsMap = Map.of(
'a', 1,
'e', 1,
//.......
'z', 10
);
Then, in your function, simply use the map to find the corresponding point for each character:
int wordPoints = 0;
for(char c : word.toCharArray())
wordPoints += pointsMap.get(c);
Use a map to store the values:
Map<Character, Integer> charValues = new HashMap();
charValues.put('a', 2);
charValues.put('b', 1);
You can use the chars() and collect as sum
int total = word.chars()
.mapToObj(c -> charValues.get((char)c))
.mapToInt(i -> (int)i)
.sum();
But according to your use case you can count the chars first and then multiply
Map<Character, Integer> counter = new HashMap<>();
while (input.hasNext()) {
String word = input.next();
word.chars().forEach(c -> counter.compute(c, (k, v) -> v == null ? 1 : v + 1));
}
counter.entrySet()
.stream()
.mapToInt(e -> charValues.get(e.getKey())*e.getValue())
.sum();
if you are using switch your code will look like:
int total = 0;
switch (c){
case 'a' : total += 1; break;
case 'b' : total += 2; break;
}
I'm not sure that the code you've shown us will compile. There are a few things you need to change;
1) You're setting a String to an int. You'll want to change that to
int point = 0
2) You aren't setting anything in the switch statement
Change case 'a': = "1": to case 'a': point = 1;
3) You will never set a unique value in the switch statement because you aren't using 'break'
Checkout this page for a good tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Basically without any break statements, your code will go through the of the statements and point will just be assigned to your last case
You want to have something along the lines of
switch(char) {
case 'a': point = 1;
break;
case 'e': point = 1;
break;
// etc.
default: point = 1; // maybe throw an error or add some logging for the default case
break;
}
return point;
I am presuming that you actually have this switch statement in it's own method and not in main as you've shown us above, otherwise the return statement won't help you.
You can also shorten this so that each case simply returns a value (again, if this is in it's own method), i.e.
switch(char) {
case 'a': return 1;
case 'b': return 1;
// etc.
}
edit:
The best way to get the point value of the whole word via a switch statement is:
char[] chars = word.toCharArray();
int point=0;
for (char c: chars) {
switch(c) {
case 'a':
point += 1;
break;
// etc.
}
}
System.out.println("Total point value of word '" + word + "' was " + point);
Instead of assigning individually for each 'case' statement, you can also use the fall through feature of the switch block.
int calcScore(String str)
{
int score = 0;
for(int i=0; i<str.length(); i++)
{
switch(str.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u': score += 1; break;
case 'g': score += 2; break;
case 'b':
case 'm':
case 'c':
case 'p': score += 3; break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y': score += 4; break;
case 'k': score += 5; break;
case 'j':
case 'x': score += 8; break;
case 'q':
case 'z': score += 10; break;
}
}
return score;
}
This function can be called for each word.
Thanks everyone, I ended up with the following code which gives the output I am after;
System.out.println("Points problem");
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + file);
System.exit(0);
} else {
System.out.println("Successfully opened file: " + file + ".");
}
//read all the lines in the file//
while (input.hasNext()) {
String word = input.nextLine();
//System.out.println(word);
int l = word.length();
int point = 0;
for (int x = 0; x < l; x++) {
char c = word.charAt(x);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u':
point += 1;
break;
case 'd':
case 'g':
point += 2;
break;
case 'b':
case 'c':
case 'm':
case 'p':
point += 3;
break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
point += 4;
break;
case 'k':
point += 5;
break;
case 'j':
case 'x':
point += 8;
break;
case 'q':
case 'z':
point += 10;
break;
}//end switch*/
}//end point calculation loop
System.out.println(word + "is worth " + point + " points." );
}

how to make a jbutton thats check if the number hexidecimal, binary,octal, decimal?

Im very new to java, newbee in short. I want to make a program that checks if the number is hexidecimal, binary, octal, decimal. And if its Hexdecimal/binary/octal convert it to decimal but if it is a decimal not convert it. in my case i made a jbutton that if its clicked it will first check the number then convert it to decimal if it is not a decimal. Now the problem is i don't know what to add to my code, at present i can only check if it is a hexidecimal and then convert it to decimal if it meets the requirements and if not it will just stay. here is my code.
private void del1ActionPerformed(java.awt.event.ActionEvent
evt) {
String hex=prime1.getText();
long dec=0;
int r=0,c=0,b,con,er;
con=(int)Math.round(inb);
String co2, tra=prime1.getText();
boolean valid;
if(valid=true){for (int i = 0; i < hex.length(); i++ ) {
int digit = hexValue( hex.charAt(i) );
if (digit == -1) {
return;
}dec = 16*dec + digit;
prime1.setText(String.valueOf(dec));
}
static int hexValue(char ch) {
switch (ch) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a': // Note: Handle both upper and lower case letters.
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return -1;
}
} // end hexValue
here prime1 is a jtextfield.
If I got you correctly, this should be what you are looking for:
int getBaseAndConvertToDecimal(String input) {
int output = -1;
for(int i=0; i<input.length(); i++) {
if(Character.isAlphabetic(input.charAt(i)) && Character.toUpperCase(input.charAt(i))<='F') {
output = 16;
}
else {
if(Character.isDigit(input.charAt(i)) && Integer.parseInt(String.valueOf(input.charAt(i)))>=8) {
output = 10;
}
else {
if(Character.isDigit(input.charAt(i)) && Integer.parseInt(String.valueOf(input.charAt(i)))>=2) {
output = 8;
}
else {
if(input.charAt(i)=='0' || input.charAt(i)=='1') {
output = 2;
}
else {
output = -1;
}
}
}
}
}
if(output != -1) {
//int this case, the output object represents the base of the input string
//Integer.parseInt(inputToConvert, destinationBase);
return Integer.parseInt(input, output);
}
return output;
}

Java - Sharing int values between cases in a switch statment

I'm new to java and not sure how do I share values between cases in a switch statement? When I try to use a variable which i created in the previous case it tells me "variable might not have been initialized"
Code:
case 6:
String stringCopy = stringInput;
String lowerCase = stringCopy.toLowerCase();
int vowelCount = 0;
int stringLength = lowerCase.length();
for (int i = 0; i <= stringLength - 1; ++i){
switch(stringInput.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowelCount++;
}
System.out.println(vowelCount);
break;
}
case 7:
int noofConstants = 0;
noofConstants = (stringLength - vowelCount);
Declare and initialize value before the switch statement.
int value = 0;
switch (key) {
case 3:
value = 1 + 1;
break;
case 4:
value = 1;
break;
you cannot access a variable that you initialize in a separate code block which is case .
declare it outside/before the code block
int stringLength = 0;
switch(){
case 6:
stringLength = 1;
break;
case 7:
stringLength = 2;
break;
}

Filling in array from end

I have a double split up into an int array, however the problem I am facing, is that I need it to fill in from the back, like this:
int[] arrayA = new int[5];
int[] arrayB = new int[5];
x = 23456.08;
//code here
//what im left with:
arrayA [0,2,3,4,5,6];
arrayB [0,8];
Heres how im cutting up the double:
public static void main(System args[])
{
Scanner input = new Scanner(System.in);
String answer = "";
int count = 0;
int thatone = 0;
int[] splitD = new int[5]; //main num
int[] splitDec = new int[1]; //decimal
//Enter the Number
System.out.print("Enter a number to convert: ");
double num = input.nextDouble();
// convert number to String
String convert = num + "";
// split the number
String[] split = convert.split("\\.");
String firstPart = split[0];
char[] charArray1 = firstPart.toCharArray();
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
// the decimal part
if (split.length > 1)
{
String secondPart = split[1];
char[] charArray2 = secondPart.toCharArray();
splitDec = new int[charArray2.length];
for (int i = 0; i < charArray2.length; i++)
{
// convert char to int
splitDec[i] = Character.getNumericValue(charArray2[i]);
}
}
for(int i =0; i<count;i++)
{
if(i ==0) // x00000.00 or 000x00.00
{
if(splitD[0] != "0")
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else
{
answer+= "";
}
}
else if(i ==1)//this goes with i =2 //0x0000
{
if(splitD[i] == 1)
{
switch (splitD[i+1])
{
case 9: answer+="Nineteen"; break;
case 8: answer+="Eighteen"; break;
case 7: answer+="Seventeen"; break;
case 6: answer+="Sixteen"; break;
case 5: answer+="Fifteen"; break;
case 4: answer+="Fourteen"; break;
case 3: answer+="Thirteen"; break;
case 2: answer+="Twelve"; break;
case 1: answer+="ten"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
thatone = 1;
}
else
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirty"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
}
}
else if(i == 2) //00x000
{
if(thatone ==0)
{
switch (splitD[i])
{
case 9: answer+=" Nine"; break;
case 8: answer+=" Eight"; break;
case 7: answer+=" Seven"; break;
case 6: answer+=" Six"; break;
case 5: answer+=" Five"; break;
case 4: answer+=" Four"; break;
case 3: answer+=" Three"; break;
case 2: answer+=" Two"; break;
case 1: answer+=" One"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
}
else
{
}
}
else if(i ==3)
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else if(i ==4) //0000x0
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirdy"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
answer+= " ";
}
else if(i ==5) //00000x
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
}
}
if(splitDec[0] == 0)
{
answer += " and 00/100 Dollars";
}
else if(splitDec[1] == 0)
{
answer += " and " +splitDec[0] + "0/100 Dollars";
}
else
{
answer += " and " +splitDec[0] +splitDec[1] +" /100 Dollars";
}
System.out.println(answer);
}
}
What should I do to make the array add 0 in the appropriate places?
such as if I typed in 54.00 I would get:
int[] SplitD = {0,0,0,0,5,4};
Thanks!
Instead of re-initializing the array:
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
Use the existing (with length = 5), iterating from the back:
if(charArray1.length > 5) // heavy hard-code, would prefer something better
throw new IllegalArgumentException("Maximum 5 digits, on both decimal sides.");
// watch out of ArrayIndexOutOfBoundsException
for (int i = charArray1.length - 1, j = splitD.length -1 ;
i >=0 && j >=0; i--, j--)
{
// convert char to int
splitD[j] = Character.getNumericValue(charArray1[i]);
count++;
}
Recall, int arrays are filled with zeros, at initialization.
Think creating an array of String, one String for each character (including the decimal point), would be a better approach:
String[] chars = String.valueOf(num).split("(?<=.)");
Job done.
Edit:
To use a switch, don't even split:
for (byte b : String.valueOf(num).getBytes()) {
switch(b) {
case '.':
case '1':
}
}

Categories

Resources