Comparing a character to an array of strings
Hi everyone, this is my first post on this forum. I'm having trouble with a program assigned for homework. I would say that I am at a beginners level in java. Here's my code in class Bug:
String[][] pathInfo = new String[5][25];
........;
........;
/*
Prints array for testing/debug use
@return pathInfo 2D array
*/
public void printArray(String[][] pathInfo)
{
for (int row = 0; row < 5; row++)
{
for (int column = 0; column < 25; column++)
{
if (pathInfo[row][column] == "*") !!!!<<<<------I think the problem lies here
{
System.out.print(pathInfo[row][column]);
}
else
{}
}
}
}
public String[][] fillArrays(String[][] pathInfo) throws FileNotFoundException
{
Scanner bugPathScan = new Scanner(new File("bugpath.txt"));
bugPathScan.useDelimiter("");
for (int row = 0; row < pathInfo.length; row++)
{
for (int column = 0; column < pathInfo[row].length; column++)
{
pathInfo[row][column] = bugPathScan.next();
}
}
return pathInfo;
}
It fills the array with info from a txt file. The text file contains a bunch of symbols, and looks something like this:
****-*--*
*-----****
*-----*--* <--my goal is to print only the '*' characters and skip the '-'
****-*--*
How could I compare the value at the current position within the array to the "*" character? I've tried changing the array type to char[][] but I can't use the scanner to read in a char value. Any ideas? Your help is greatly appreciated
Re: Comparing a character to an array of strings
.equals() not ==
I think..
Re: Comparing a character to an array of strings
An extension of what ppme said:
When comparing two string literals, it is best to use the .equals() method to compare if each char is the same, rather than the == comparison operator that will check if both objects are the same.
However if you want to compare chars, use single quotation marks. EG
Code Java:
/*
* Precondition: c1 is a char.
*/
if(c1 == 'a')
{
//Not included
}
For getting a specific char at an index in a String, look at the charAt method in the String API:
String (Java Platform SE 6)
Re: Comparing a character to an array of strings
Thanks for the tip! Using the .equals method "if (pathInfo[row][column].equals('*'))" lets it compile but its still not printing anything. I'm not sure where the problem lies now though :/
Re: Comparing a character to an array of strings
No problem, however string literals aren't chars.
pathInfo[row][column] is a string, but '*' is a char, so you are comparing a String to a char, which I'm surprised compiles.
Double quotes(") makes "*" a string, which you can use to compare to pathInfo.