Originally Posted by
sp11k3t3ht3rd
Okay, I'm kind of new to Java but I still know some stuff. I'm trying to get a string value from a separate class that is within a method in that class. I can't figure it out! I'm making a tic-tac-toe game ( Text-Based ).This is the code for the computer moving class.
public class compMove {
String compChoice;
public String move() {
String[] rowsComp = {"(1,1)", "(1,2)", "(1,3)", "(2,1)", "(2,2)", "(2,3)", "(3,1)", "(3,2)", "(3,3)"};
int rowsCompLength = rowsComp.length;
int rand = (int) (Math.random() * rowsCompLength);
compChoice = rowsComp[rand];
System.out.println(compChoice);
return ("compChoice");
}
}
This is the code for the spaces that can be selected by either an X or an O.
public class space {
String space11 = "-";
String space12 = "-";
String space13 = "-";
String space21 = "-";
String space22 = "-";
String space23 = "-";
String space31 = "-";
String space32 = "-";
String space33 = "-";
public void space11 () {
compMove computer = new compMove();
computer.move();
if(computer.move().compChoice.equals("(1,1)")) {
space11 = "o";
}
}
public void printSpace11() {
space11 ();
}
}
As you can see I am trying to check if the value of the string compChoice which gets its value in the method move in the compMove class is equal to (1,1). This code does not compile but can someone tell me how to fix this line of code to work?
if(computer.move().compChoice.equals("(1,1)"))
Please Help!
It depends, if you defined that String inside that method, it's lost after the method ends. However, if the method returns that String, then you could call that String by
TheOtherClass toc = new TheOtherClass(parameters)
to get to the string in TheOtherClass, if it's returned by the method:
wait...if you're comparing a String in your current class to a String that is returned by the method in the other class, you do this:
TheOtherClass toc = new TheOtherClass(parameters);
String str = "whatever";
String str2 = toc.theMethod(methodsParameters);
if (str.equals(str2))
{
// whatever
}
if you aren't returning it from that method, and you have that particular String as a public value in the constructor, then you can, maybe, get it by calling it like this:
TheOtherClass toc = new TheOtherClass(parameters)
String str = "whatever";
String str2 = toc.otherStringVariableName;
// note, this will set it to null if it hasn't been set. It may only return what the constructor has set it to.
// I'm not certain on this one, but it can't hurt to try.
if (str.equals(str2))
{
// whatever
}
Unless you're comparing length or something else. Then do that comparison then if so.