Take different actions depending on jTextField value - java

I have many more cases, but I'm wondering if there is a simpler way to do this. If the user enters 1 the program will convert from inches to cm, if the user enters 2, the program will convert from cm to feet, etc.
if (jTextField1.getText() == 1) {
InchesToCm();
} else if (jTextField1.getText() == 2) {
CmToFeet();
} else if (jTextField1.getText() == 3) {
MetresToYards();
} else if (jTextField1.getText() == 4) {
KmToMetres();
} else {
jLabel8.setText("Error, try again");
}

It depends on your definition of 'simpler' but you could use a switch statement. Like so:
switch(Integer.parseInt(jTextField1.getText())){
case 1:
InchesToCm();
break;
case 2:
CmToFeet();
break;
case 3:
MetresToYards();
break;
case 4:
KmToMetres();
break;
default:
jLabel8.setText("Error, try again");
break;
}
This way you don't have to use a chain of if statements but if it's simpler is up to you.
I hope this helps :)

Related

How to make an if statement with multiple variables and multiple conditions into a switch case ? Can && compare cases?

I'm making a rock paper scissors game for school and I have a working game but its 213 lines long. I was trying to shorten it up some by adding switch case in place of my if statements. Are there some instances where a switch case just won't work and it has to be an if statement?
String weaponChoice = keyboard.nextLine();
switch (weaponChoice) {
case "Rock":
System.out.println("You Chose Rock");
break;
case "Paper":
System.out.println("You Chose Paper");
break;
case "Scissors":
System.out.println("You chose Scissors");
break;
default:
System.out.println(weaponChoice + " is not a valid answer the computer gets a point!");
compScore++;
break;
}
I had the above code in an if statement and switched it over no problem but the below code I'm not sure how to change it over.
String getComputerChoiceVariable = getComputerChoice();
System.out.println("The computer chose " + getComputerChoiceVariable);
if (weaponChoice.equals(getComputerChoiceVariable)) {
System.out.println("It's a draw!");
ties++;
} else if ((weaponChoice.equals("Rock")) && (getComputerChoiceVariable.equals("Scissors"))) {
System.out.println("You won!");
userScore++;
} else if ((weaponChoice.equals("Paper")) && (getComputerChoiceVariable.equals("Rock"))) {
System.out.println("You won!");
userScore++;
} else if ((weaponChoice.equals("Scissors")) && (getComputerChoiceVariable.equals("Paper"))) {
System.out.println("You won!");
userScore++;
} else if (weaponChoice.equals("Rock") && getComputerChoiceVariable.equals("Paper")) {
System.out.println("You Lost!");
compScore++;
} else if (weaponChoice.equals("Paper") && getComputerChoiceVariable.equals("Scissors")) {
System.out.println("You Lost!");
compScore++;
} else if (weaponChoice.equals("Scissors") && getComputerChoiceVariable.equals("Rock")) {
System.out.println("You Lost!");
compScore++;
}
Maybe something like
switch (weaponChoice,getComputerChoiceVariable){
case "Rock",case "Scissors":
System.out.println("You won!");
}
But Java doesn't like that I get a ton of errors. Can a switch take two parameters?
I'm super new to Java.
Could I somehow use the && to compare cases?
A switch statement can test the value of only one expression. It is possible to nest switch statements, but that's overly verbose and is no better than a series of if/else statements.
As an aside, you may want to validate the user's weapon of choice, so someone doesn't choose Lizard, Spock, Foo, or something else unexpected.
You can concatenate the strings into one so it can be tested. I would use a separator such as "|" to make the choices clear. Also, different cases have the same logic, avoiding repetition.
switch(weaponChoice + "|" + computerChoice)
{
case "Rock|Scissors":
case "Scissors|Paper":
case "Paper|Rock":
System.out.println("You won!");
userScore++;
break;
case "Rock|Paper":
case "Paper|Scissors":
case "Scissors|Rock":
System.out.println("You lost!");
compScore++;
break;
default:
System.out.println("It's a draw!");
ties++;
}
This is concise and it lists all similar cases together, without repetition.
A switch block cannot be written with two parameters. From Oracle's documentation:
A switch works with the byte, short, char, and int primitive data
types. It also works with enumerated types (discussed in Enum Types),
the String class, and a few special classes that wrap certain
primitive types: Character, Byte, Short, and Integer (discussed in
Numbers and Strings).
However, you could make your program more modular by writing:
if (weaponChoice.equals(getComputerChoiceVariable)) {
System.out.println("It's a draw!");
ties++;
} else if (userWins(weaponChoice, getComputerChoiceVariable)) {
System.out.println("You won!");
userScore++;
} else {
System.out.println("You Lost!");
compScore++;
}
and using something like:
public boolean userWins(String userWeapon, String compWeapon) {
if((userWeapon.equals("Rock")) && (compWeapon.equals("Scissors"))) {
return true;
} else if((userWeapon.equals("Paper")) && (compWeapon.equals("Rock"))){
return true;
} else if((userWeapon.equals("Scissors")) && (compWeapon.equals("Paper"))){
return true;
} else if(userWeapon.equals("Rock") && compWeapon.equals("Paper")) {
return false;
} else if(userWeapon.equals("Paper") && compWeapon.equals("Scissors")) {
return false;
} else {
return false;
}
}
You don't necessarily need to make a switch of your code to shorten it. You can put the tree options in a list, and compare the user's choice with the value that that comes after the computer's choice to see if the user won.
If you have the list [Rock, Paper, Scissors], the computer chose Rock. Find the element after it, so Paper in this case. Now you only have to see if that value is equal to the user's choice, and if that's the case, the user won.
List<String> choices = Arrays.asList("Rock", "Paper", "Scissors");
if (playerChoice.equals(computerChoice)) {
System.out.println("Draw!");
} else if (playerChoice.equals(choices.get((choices.indexOf(computerChoice) + 1) % 3))) {
System.out.println("You won!");
} else {
System.out.println("You lost!");
}
Here choices.indexOf(computerChoice) finds the current positions of the computer's choice in the list. It add's one to find the next element in the list and uses the remainder operator (% 3) to make sure that if the next index is higher than the last element in the list, it flips back to the first element.

How to break out of loop when case is selected

I have a code that has 4 cases and I am trying to break the loop and if the 'f' case is chosen. and then choose from that case. When i try to do the if statement with the break over 30 errors but when I take it away the code is fine.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
}
if (case == 'f')
{
break;
}
}
You would use a Java label (see this code example named BreakWithLabelDemo.java) to tell your code where to break.
myloop:
while ( true ){
switch( choice ){
case 'f':
friendsList();
break myloop;
}
}
For your implementation, it would make sense to break on a specific case before even entering the switch statement. For example:
char choice = one.charAt(0);
if (choice == 'f') break;
switch(choice)
This seems to be a pretty simple way to exit the while loop without conflicting with the break statements of the switch statement.
Or if you still need to call the friendsList method when choice is 'f' you can move that if statement to after the switch statement.
Note: With this you should also remove the if statement at the bottom of your code example.
if (case == 'f')
What is case in this statement? You should replace that with choice.
if (choice == 'f')
you need to put if inside while loop.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
if (choice == 'f')
{
break;
}
}
The if statement should be moved inside of the while loop to be effective, and case inside the if statement should be changed to choice.
so
While(yea==true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
if(choice == 'F')
{
break;
}
switch(choice)
{
//cases
}
}

sorting by first character

The question at hand is each policy No. is a string of 9 characters of which indicates the type of insurance policy
B for building policy
C for Contents Policy
L for Life policy
V for car policy
Each of the remaining 8 characters of the policy number is a decimal digit.
I have tried using charAt but somebody told me there was a slightly better way
public String getpolicyNo(String initpolicyNo) {
/**
* Access method to find the first character of the policy to then
* determine what type of policy it is.
*/
String b = "B";
String C = "C";
String L = "L";
String V = "V";
char c1 = b.charAt(0);
char c2 = C.charAt(0);
char c3 = L.charAt(0);
char c4 = V.charAt(0);
if (c1 == 0) {
System.out.println("Its building" + c1);
return initpolicyNo;
} else {
if (c2 == 0) {
System.out.println("Its Content");
return initpolicyNo;
} else {
if (c3 == 0) {
System.out.println("Its life");
return initpolicyNo;
} else {
if (c4 == 0) {
System.out.println("Its car");
return initpolicyNo;
}
}
}
}
throw new IllegalArgumentException();
}
I'm not looking for you to provide an answer for me, I'm just looking for any possible alternatives and possible suggestions.
Many thanks
Dan
I'm not really sure what you are trying to achieve, but I would write this way:
public String getpolicyNo(String initpolicyNo) {
switch(initPolicyNo.charAt(0))
{
case 'B':
System.out.println("Its building B");
return initpolicyNo;
case 'C':
System.out.println("Its building C");
return initpolicyNo;
case 'L':
System.out.println("Its building L");
return initpolicyNo;
case 'V':
System.out.println("Its building V");
return initpolicyNo;
}
throw new IllegalArgumentException();
}
I recommend you using an Enum. Each value for an Enum has an ordinal value, which you can sort by.
If you want to read an introduction to Enums, the following site will help: Enum Types - The Java Tutorials
enum Policy {
BUILDING_POLICY, CONTENTS_POLICY, LIFE_POLICY, CAR_POLICY
}
For each enum value, you can assign a custom value, with which you can sort.
public void whatItIs(String s){
if(s.length() < 1){
//-- nothing to see here ---
return;
}
//-- case insensitive --
char c = Character.toUpperCase(s.charAt(0));
switch(c){
case 'B':
//-- its a building !--
break;
case 'C':
//-- its a c........ !--
break;
case 'L':
//-- its a l........ !--
break;
case 'V':
//-- its a v........ !--
break;
default:
//-- its something else :(--
}
}
public String getpolicyNo(String initpolicyNo) {
switch (initpolicyNo.charAt(0)) {
case 'B':
System.out.println("Its building" );
break;
case 'C':
System.out.println("Its Content");
break;
case 'L':
System.out.println("Its life");
break;
case 'V':
System.out.println("Its car");
break;
default:
throw new IllegalArgumentException();
break;
}
return initpolicyNo;
}
You could add enums to your code, or you could use a switch statement instead of the if/else block you currently have:
char type = initpolicyNo.charAt(0);
switch (type) {
case 'B':
// do stuff
break;
case 'C':
// do stuff
break;
}
Note: I think you may have a problem in your code in that it seems to me you should be switching on the initpolicyNo, not the actual types?
I have tried using charAt but somebody told me there was a slightly
better way
there is no better way to get the first letter of a string than using charAt.
And rather than having lots of if's/switches and what not, get a bit more OOPs up side your head.
Map<Character, String> myMap = new HashMap<Character, String>() {{
put('B', "Its building");
put('C', "Its content");
put('L', "its life");
put('V', "its vehicle");
}} ;
public void iShouldBeDoingMyOwnWork(String initpolicyNo) {
System.out.println(myMap.get(initpolicyNo.charAt(0)));
}

how to compare more than two Strings in Java?

I have 4 strings s1,s2,s3,s4. and i want to compare it with "yes","no" and "both"
It has to be like (s1.equals("yes"));
if ALL strings are equal to "yes" it should give one result.
if ALL strings are equal to "no" it should give one result.
if any 2 strings are equal to "yes" and another 2 strings are equal to "no" it has to give one result.
if any 3 strings are equal to "yes" and 1 string equal to "no" it has to give one result.
if any 3 stings are equal to "no" and 1 string is equal to "yes" it has to give one result..
How to do this comparison?
I would store those strings in a list, and use Collections utility to find the frequencies of yes and no. Then apply your conditions to number of yes and no.: -
List<String> list = new ArrayList<String>() {{
add("yes"); add("yes"); add("no"); add("no");
}};
int yes = Collections.frequency(list, "yes");
int no = Collections.frequency(list, "no");
if (yes == 4 || yes == 0) { // all "yes" or all "no"
System.out.println("Operation 1");
} else if (yes == 2) { // 2 "yes" and 2 "no"
System.out.println("Operation 2");
} else { // (1 "yes", 3 "no") or (1 "no", 3 "yes")
System.out.println("Operation 3");
}
Of course, I assume that your strings can only be "yes" or "no".
Assuming they are either "yes" or "no", use this:
int yesCount = (s1+s2+s3+s4).replace("no", "").length() / 3;
Then base your logic on that, possibly with a switch(yesCount)
You can try this logic. This one does what you intend to do :
if(s1.equals("yes") && s2.equals("yes") && s3.equals("yes") && s4.equals("yes"))
result1;
else if (s1.equals("no") && s2.equals("no") && s3.equals("no") && s4.equals("no"))
result2;
else if ((s1.equals("yes") || s2.equals("yes")) && (s3.equals("no") || s4.equals("no")))
result3;
else if((s1.equals("yes") || s2.equals("yes") || s3.equals("yes")) && s4.equals("no"))
result4;
else if((s1.equals("no") || s2.equals("no") || s3.equals("no")) && s4.equals("yes"))
result5;
String[] str={s1,s2,s3,s4};
int yesCount=0, noCount=0;
for(int i=0;i<str.length();i++){
if("yes".equals(str[i]))
yescount++;
else if("no".equals(str[i]))
noCount++;
}
String check=""+yesCount+noCount;
switch(check){
case "40":
//do whatever
break;
case "30":
//do whatever
break;
case "20":
//do whatever
break;
case "10":
//do whatever
break;
case "31":
//do whatever
break;
case "21":
//do whatever
break;
case "11":
//do whatever
break;
case "22":
//do whatever
break;
case "12":
//do whatever
break;
case "13":
//do whatever
break;
case "04":
//do whatever
break;
case "00":
//do whatever
break;
}
Assuming string value can be either yes or no
int result = 0;
if("yes".equalsIgnoreCase(s0)) result++;
if("yes".equalsIgnoreCase(s1)) result++;
if("yes".equalsIgnoreCase(s2)) result++;
if("yes".equalsIgnoreCase(s3)) result++;
switch(result){
case 0:
System.out.println("all strings are NO");
break;
case 1:
System.out.println("3 strings are NO, 1 string is YES");
break;
case 2:
System.out.println("2 strings are NO, 2 strings are YES");
break;
case 3:
System.out.println("1 string is NO, 3 strings are YES");
break;
case 4:
System.out.println("all strings are YES");
break;
}

Having trouble with user input validation

This is a small part of my program that I am working on. I'm trying to check if the user enters the correct number.
They have five choices to choose from so they can either hit 1, 2, 3, 4, or 5. Then press enter.
So I want to check to make sure the user doesn't type anything in < 1 or > 5. I got that part to work... But I just want to know if there is a easier way to do it then from what I did in code below.
The next part is that I also want to make sure the user doesn't type in letters. like "gfgfadggdagdsg" for a choice.
Here is my code of the part I am working on....
public void businessAccount()
{
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
if (selection > 5){
System.out.println("Invalid choice.");
businessAccount();
}
else if (selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}
else {
switch(selection)
{
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
}
You may get rid of checking < 1 and > 5 by adding a default case.
try{
selection = input.nextInt();
switch(selection){
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
break;
default:
System.out.println("Invalid choice.");
businessAccount();
}
}catch(InputMismatchException e){
//do whatever you wanted to do in case input is not an int
}
Using BufferedReader you can do something like this:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
int selection = 0;
try{
selection = Integer.parseInt(s);
if(selection > 5 || selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}else{
// your switch code here
}
// you can use #Nishant's switch code here. it is obviously better: using switch's default case.
}catch(NumberFormatException ex){
// throw new Exception("This is invalid input"); // or something like that..
System.out.println("Invalid choice.");
businessAccount();
}
Hope that helps.
Note: you must import java.lang.NumberFormatException import java.io.InputStreamReader and import java.io.BufferedReader
Use the switch case it's better and more speed the if statement when you check selection from a Specific.
an alternative would to use regular expressions to get it work.
Say you have a string x then
String x = "something";
if(x.matches("regex")){
}
Another way to do this is surround with try catch.

Categories