how to compare more than two Strings in Java? - 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;
}

Related

Bad practice when I want to check like this if an int is this number?

I have to check if my int n equals 1 or 2 or 3 or 4 or 5 or 6
Is it bad practice to do it like this:
//n = randomnumber
private final List<Integer> numbers = Arrays.asList(0,1,2,3,4,5,6);
if(numbers.contains(n)){
return;
}
or should I do a switch?
switch(n){
case 1:
return;
break;
case 2:
return;
break;
//...
case 6:
return;
break;
}
I could also do if statmements but I guess I dont have to

Scanner returning an error for no reason?

I'm trying to do this line of code. I want it to take a String, if it is 1,2,3,4,5,6,7,8,9 or 10 to parse it into a int and then check if it is between 0 and 9 (after a -1). The issue is right after the scanner happens I get an error no matter what I do...
public void guessEnter() {
Scanner scan = new Scanner(System.in);
String guessXS;
String guessYS;
boolean pass1;
boolean pass2;
do{
do{
System.out.println("Enter a value for the column!");
guessXS = scan.nextLine();
switch(guessXS){
case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9":case "10":
System.out.println("TRUE");
pass1 = true;
break;
default:
System.out.println("FALSE");
pass1 = false;
break;
}
}while(pass1 == false);
do{
System.out.println("Enter a value for the row!");
guessYS = scan.nextLine();
switch(guessYS){
case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10":
pass2 = true;
System.out.println("TRUE");
break;
default:
pass2 = false;
System.out.println("FALSE");
break;
}
}while(pass2 == false);
guessX = Integer.parseInt(guessXS) - 1;
guessY = Integer.parseInt(guessYS) - 1;
}while(guessX >= 0 && guessX <= 9 && guessY >= 0 && guessY <= 9);
}
Why this is happening is beyond me. I am fairly new to java and need this error sorted out.
The error is...
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at shipLocation.xyInput(shipLocation.java:11)
at battleShipMain.main(battleShipMain.java:53)
Thanks for the help.
Even if the question has already been answered (the error was in a different class) and the provided code caused no error you maybe want to improve your code a bit. To make it easier to read and understand in case you have to change it later.
You could for example wrap the input and validation part in a method:
private int readIntBetweenMinAndMax(String msg, int min, int max) {
Scanner scanner = new Scanner(System.in);
System.out.println(msg);
int userInput;
do {
try {
userInput = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.err.println("Please enter a valid integer");
continue;
}
if (userInput > max || userInput < min) {
System.err.println("Please enter a integer between " + min + " and " + max);
continue;
}
return userInput;
} while (true);
}
The method above prints a provided string msg and then reads in an integer. It checks if the user input is an integer and if it's greater or equals than min and less or equals than max. In case one of the three conditions fails the method will print an error message and prompt the user for a new input until its correct.
Note: You could of course also include the "TRUE" and "FALSE" outputs if you want
So you would only have to call the method two times in your guessEnter method:
public void guessEnter() {
guessX = readIntBetweenMinAndMax("Enter a value for the column!", 1, 10) - 1;
guessY = readIntBetweenMinAndMax("Enter a value for the row!", 1, 10) - 1;
}
This would accept one, ten and any number between the them. And subtract one as you did in your code.
As a said, it's just a suggestion and I'm not sure if a got everything form your code right but I hope it helps (:

Take different actions depending on jTextField value

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

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

Switching String to Integer

I need the syntax for adding in the variable parameter to a switch case that already has lots of parameters. The context is provided below.
I'm using a switch case to change a string answer to an integer return. Instead of having the user answer
1. This.
2. Something else.
I want the answer to look like
(y/n)
I've done it before with a code like this:
static public int getYN() {
String answer = "";
switch(keyboard.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
And then using the statement:
int getAnswer = getYN();
System.out.println();
if (getAnswer == 1) {
System.out.println("Stuff.");
test = 1;
}
else {
System.out.println("Other stuff.");
System.out.println();
}
But, I don't know where to put the String answer variable into the switch case. Usually, if you aren't using many other parameters, it would just be
switch(answer) {
}
Check it inline, forget having a dedicated method to doing this check.
char getAnswer = keyboard.next().charAt(0);
System.out.println();
if (getAnswer == 'y' || getAnswer == 'Y')
{
System.out.println("Stuff.");
test = 1;
}
else if( getAnswer == 'n' || getAnswer == 'N')
{
System.out.println("Other stuff.");
System.out.println();
}
If you absolutely have to use a switch:
char getAnswer = keyboard.next().charAt(0);
switch(getAnswer)
{
case 'y':
System.out.println("Stuff.");
test = 1;
break;
case 'n':
System.out.println("Other stuff.");
System.out.println();
break;
}
You can achieve the same thing in one line:
public static int getYN(String s) {
return ("yn YN".indrxOf(s) + 3) % 3;
}
Both upper and lower cases are handled, and the "not found" default value of 2 is handled by adding 3 (indexOf() returns -1 when the target is not found) and modulus divusion takes care of the capital letter indexes.
Fairly neat even if I do say so myself.

Categories