This question has already been answered:
- How to compare strings in java? 2 answers
I am writing a class in which there is a method (acceptSelection) that accepts a user move as a string of type "A3", "B4" and the like. In this method, the character is separated from the number. As a result, four variables are obtained: word1, number1, word2, word2, which are string and numeric representations of the user course, respectively. That is, let's say, there were moves A3 and B4, so word1 = "A", word2 = "B", number1 = 3, number2 = 4. After that, it is necessary to determine their indices in the array from the method (getScore).
public class ExampleOne { private static int number1; private static int number2; private static String word1; private static String word2; private static int index1; private static int index2; private static String a3 = "A3"; private static String b4 = "B4"; public static void main (String args[]) { acceptSelection(a3, b4); System.out.println("Index 1 " + index1); System.out.println("Index 2 " + index2); } public static int getScore (String df, int b) { int totalScore=0; if (a=="A") { totalScore = (0+b)-1; //return totalScore; } else if (a=="B") { totalScore = (4+b)-1; //return totalScore; } else if (a=="C") { totalScore = (8+b)-1; //return totalScore; } else if (a=="D") { totalScore = (12+b)-1; //return totalScore; } else if (a=="E") { totalScore = (16+b)-1; //return totalScore; } else if (a=="F") { totalScore = (20+b)-1; //return totalScore; } else if (a=="G") { totalScore = (24+b)-1; //return totalScore; } return totalScore; } public static void acceptSelection (String a, String b) { Pattern number = Pattern.compile("[0-9]"); Matcher m = number.matcher(a); Matcher m1 = number.matcher(b); while (m.find()) { number1 =Integer.parseInt(a.substring(m.start(), m.end())); } while (m1.find()) { number2 =Integer.parseInt(b.substring(m1.start(), m1.end())); } Pattern word = Pattern.compile("[a-zA-Z]"); Matcher w = word.matcher(a); Matcher w1 = word.matcher(b); while (w.find()) { word1 = a.substring(w.start() , w.end()); } while (w1.find()) { word2 = b.substring(w1.start() , w1.end()); } index1 = getScore(word1, number1); index2 = getScore(word2, number2); } When the getScore method is called in this way, index1 = getScore (word1, number1), a zero totalScore is returned. However, if you call the method like this: index1 = getScore ("A", 3) everything works correctly. I can not understand what the problem is. It seems that the problem lies in the simple, just can not see.
equals(), not==: for example,a.equals("A")will work this way, but I would recommend that you completely rework all this code, it is terrible (nothing personal) - pavlofff