Java - Sharing int values between cases in a switch statment - java

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

Related

Does break in a switch-statement terminates a for-loop?

I am trying to understand return, break and continue.
I know that break will stop the (inner) for loop. For example:
for (int i = 1; i <= 3; i++) {
// inner loop
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
// using break statement inside the inner loop
break;
}
System.out.println(i + " " + j);
}
}
I know the outer loop will go on.
What I don't understand is this here:
for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break;
case 1:
line = "How are you?";
break;
case 2:
line = "What are you doing?";
break;
So it goes to case 0 and then break and the for-loop continues, why? I thought it will break the loop since it's not nested.
Or is it because of the switch-statement - it's different than if-statements?
And in this case, it will terminate the whole while-loop... I can't see the difference.
while(winner == false){
input = menuInput.nextInt();
try {
if(input == 0 || input >= 9){
System.out.println("Ungültige Nummer, versuche nochmal!");
break;
}
You can break a switch. You can't break an if. break is applied to the closest statement that could be breaked, so
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
// using break statement inside the inner loop
break;
}
System.out.println(i + " " + j);
}
Here break refers to the for.
While here:
for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break;
It refers to the switch.
Statements that can be breaked are for, while, do...while, switch.
For further info, you can see the spec.
The break applies to the inner-most thing which can be break'd (without a label). In this case, it's the switch - because the default switch behavior falls through. First, your code. Change,
for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break;
case 1:
line = "How are you?";
break;
case 2:
line = "What are you doing?";
break;
Could be changed to
loop: for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break loop;
case 1:
line = "How are you?";
break loop;
case 2:
line = "What are you doing?";
break loop;
Now, the second behavior would be fall-through. And that might look something like,
switch (a) {
case 0: case 2: case 4: case 6: case 8:
System.out.println("even < 10");
break;
case 1: case 3: case 5: case 7: case 9:
System.out.println("odd < 10");
break;
}
In switch, statement break means to end switch statement. Take a look at fall trough example.
In the loop, statement break means to end a loop.
Stop looping after using switch statement example:
for (int i = 0; i < 3; i++) {
Boolean shouldBreak = false;
String line = null;
switch (a) {
case 0:
line = "Hello";
shouldBreak = true;
break;
case 1:
line = "How are you?";
shouldBreak = true;
break;
}
if (shouldBreak){
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 add 14 based numbers in instance method?

So I'm having trouble with creating an instance method to add two 14-based number and I was wondering if anyone could help? I'm a bit new to java and still sort of confused on the whole thing. So far I have the code to convert the 14-based numbers to base 10 then I need to add them and convert them back to base-14. I want to put them all in once instance class, but I feel like it's too much to put into one instance class.
This is the kind of input I was for the client code to be like this:
PokerNum sum = num1.add(num2);
import java.util.Scanner;
public class PokerNum{
String alienNum;
int num1, num2;
public PokerNum(String alienNum) throws IllegalArgumentException{
this.alienNum = alienNum;
String toUpper = alienNum.toUpperCase();
for (int i = 0; i < toUpper.length(); i++){
char c = toUpper.charAt(i);
if (!(Character.isDigit(c) || c == 'A' || c == 'J' || c == 'Q' || c == 'K')){
throw new IllegalArgumentException("invalid input");
}
}
}
// initialized at zero
public PokerNum() {
this.num1=0;
this.num2=0;
}
#Override public String toString(){
return PokerNum()+ " ";
}
//add pokernums
public PokerNum add(PokerNum another){
PokerNum num = new PokerNum();
this.num1 = another.num1;
this.num2 = another.num2;
public PokerNum convert(PokerNum pn){
char[] firstNum = num1.toCharArray();
int amountValue = 0;
int length = characters.length;
for (int index = 0; index < length; index++){
int symbolValue;
switch (characters[index]) {
case 'A':
symbolValue = 10;
break;
case 'J':
symbolValue = 11;
break;
case 'Q':
symbolValue = 12;
break;
case 'K':
symbolValue= 13;
break;
default:
symbolValue = characters[index] - 48;
}
amountValue += symbolValue*Math.pow(14, length - index - 1);
}
StringBuilder result1 = new StringBuilder();
while(amountValue > 0){
int digit = amountValue%14;
switch (digit) {
case 10:
result.insert(0, 'A');
break;
case 11:
result.insert(0, 'J');
break;
case 12:
result.insert(0, 'Q');
break;
case 13:
result.insert(0, 'K');
break;
default:
result.insert(0, digit);
}
amountValue-=digit;
amountValue/=14;
String firstValue = result1.toString();
}
}
char[] secNum = num2.toCharArray();
int amountValue2= 0;
int length = secNum.length;
for (int index = 0; index < length; index++){
int symbolValue;
switch (characters[index]) {
case 'A':
symbolValue = 10;
break;
case 'J':
symbolValue = 11;
break;
case 'Q':
symbolValue = 12;
break;
case 'K':
symbolValue= 13;
break;
default:
symbolValue = characters[index] - 48;
}
amountValue2+= symbolValue*Math.pow(14, length - index - 1);
}
StringBuilder result = new StringBuilder();
while(amountValue2> 0){
int digit = amountValue%14;
switch (digit) {
case 10:
result.insert(0, 'A');
break;
case 11:
result.insert(0, 'J');
break;
case 12:
result.insert(0, 'Q');
break;
case 13:
result.insert(0, 'K');
break;
default:
result.insert(0, digit);
}
amountValue2-=digit;
amountValue2/=14;
PokerNum secondValue = result.toString();
}
return firstValue + secondValue;
/*PokerNum sum = num1 +
PokerNum another.num2 =
return sum;*/
}
Thanks to anyone who helps in advance :)
I believe you can keep it in one instance. One suggestion is to use the conversion using the following functions:
Integer.parseInt(String s, int radix)
Integer.toString(int i, int radix)
The javadoc says that the string produced will use:
0123456789abcdefghijklmnopqrstuvwxyz
So, if we choose radix = 14, it will have 0123456789abcd.
The logic idea is to keep the actual number as int, and to convert at creation and at printout from and to String. We can just keep member variable num1 and remove the member variable alienNum and num2.
Constructor
Your constructor with String argument seems to do a good error checking. What we need here is just to convert from string to integer and store it in the member variable. First we need to convert all valid string from AJQK to ABCD. The example here is inefficient, but gets the idea across:
//alienNum = alienNum.replace('A', 'A'); // no need
alienNum = alienNum.replace('J', 'B');
alienNum = alienNum.replace('Q', 'C');
alienNum = alienNum.replace('K', 'D');
Then we can call the parsing method:
num1 = Integer.parseInt(alienNum , 14);
Your empty arg constructor is already fine by initializing the value of num1 to 0.
Adding
The method inside addition is not right because it is setting the current value to the addition. There are three objects working here: num, this, and another. You want to add this to another into num and return num.
num.num1 = this.num1 + another.num1;
Output
I'm assuming the output is going to be from toString(). In this case, you want to convert from integer to string, then convert it to the right character
String out = Integer.toString(num1, 14).toUpper();
//alienNum = alienNum.replace('A', 'A'); // no need
alienNum = alienNum.replace('B', 'J');
alienNum = alienNum.replace('C', 'Q');
alienNum = alienNum.replace('D', 'k');
You probably won't need a convert method now.

How to convert If statement to switch statement?

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

Using a non-constant expression in a switch statement?

I'm quite new to java and have created a Java class that creates a deck of cards, and assigns them a suite, a name, a value and an ID. The problem is, there are 52 different cards that require an ID, and I've been using switch statements to assign the name, value and suite. However, if I were to do this for the card ID, I would need 52 lines of case statements, which is far too many.
public class Deck {
private Card[] cards;
public Deck() {
String suit = null;
String name = null;
int cardID=0;
int value = 0;
cards = new Card[52];
int arrayID=0;
for (int i=1; i<=4; i++){ //number of suites
for (int j=1; j <= 13; j++){ //number of card types
for (int k=1; k==52; k++){ //number of cards
switch (i){
case 1: suit = "Clubs"; break;
case 2: suit = "Diamonds"; break;
case 3: suit = "Hearts"; break;
case 4: suit = "Spades"; break;
}
switch (j){
case 1: name = "Ace"; value = 11; break;
case 2: name = "Two"; value = 2; break;
case 3: name = "Three"; value = 3; break;
case 4: name = "Four"; value =4; break;
case 5: name = "Five"; value = 5; break;
case 6: name = "Six"; value = 6; break;
case 7: name = "Seven"; value = 7; break;
case 8: name = "Eight"; value = 8; break;
case 9: name = "Nine"; value = 9; break;
case 10: name = "Ten"; value = 10; break;
case 11: name = "Jack"; value = 10; break;
case 12: name = "Queen"; value = 10; break;
case 13: name = "King"; value = 10; break;
}
switch (k){
case k: cardID=k; break; //"Case expressions must be constant expressions"
}
Card card = new Card (cardID, name, suit, value);
cards[arrayID] = card;
arrayID++;
}
}
}
}
public void printDeck(){
System.out.println(Arrays.toString(cards));
}
}
I may be doing this whole thing wrong, so are there any other ways I could assign a unique ID to the card without using a switch statement?
There's no point in this switch statement :
switch (k){
case k: cardID=k; break; //"Case expressions must be constant expressions"
}
Just write :
cardID = k;
You could use enum and you could use ordinal value to get each count automatically and you could have property like value in your case and you could do it like:
public enum Cards {
ACE(11), TWO(..), .. JACK(....;
int value;
public int getValue() {return value;}
}
System.out.println(CARDS.ACE.ordinal() + 1);
System.out.println(CARDS.ACE.getValue());
Output:
1
11
You don't need the loop or the switch statement for the cardID. You can synthesize it from i and j
for (int i=1; i<=4; i++){ //number of suites
for (int j=1; j <= 13; j++){ //number of card types
cardId = (i - 1) * 13 + j; // <<< synthesize cardID like this
switch (i){
case 1: suit = "Clubs"; break;
case 2: suit = "Diamonds"; break;
case 3: suit = "Hearts"; break;
case 4: suit = "Spades"; break;
}
switch (j){
case 1: name = "Ace"; value = 11; break;
case 2: name = "Two"; value = 2; break;
case 3: name = "Three"; value = 3; break;
case 4: name = "Four"; value =4; break;
case 5: name = "Five"; value = 5; break;
case 6: name = "Six"; value = 6; break;
case 7: name = "Seven"; value = 7; break;
case 8: name = "Eight"; value = 8; break;
case 9: name = "Nine"; value = 9; break;
case 10: name = "Ten"; value = 10; break;
case 11: name = "Jack"; value = 10; break;
case 12: name = "Queen"; value = 10; break;
case 13: name = "King"; value = 10; break;
}
Card card = new Card (cardID, name, suit, value);
cards[arrayID] = card;
arrayID++;
}
}
What I would do is instead:
Create a class card:
class Card {
private String suit;
private String name;
private int ID;
public Card(String suit, String name, int ID) {
this.suit = suit
(same for name & ID)}}
Then, in your Deck class, you can just have a ArrayList that contains all your card, with some method to add the cards in your deck:
s
class Deck {
private ArrayList<Cards> myDeck = new ArrayList<Cards>();
public void addCards(Card myCard) {
this.myDeck.add(myCard); } }
EDIT: Forgot the variable type in addCards

Categories

Resources