数组存储了所有信息,我觉得这个程序真的很接近工作。我知道它不整洁,我会立即清理它!问题在底部。
public class FoodFacts
{
private static BufferedReader textIn;
private static BufferedReader foodFacts;
static int numberOfLines = 0;
static int NUM_COL = 7;
static int NUM_ROW = 961;
static String [][] foodArray = new String[NUM_ROW][NUM_COL];
public static String fact;
// Make a random number to pull a line
static Random r = new Random();
public static void main(String[] args)
{
try
{
textIn = new BufferedReader(new InputStreamReader(System.in));
foodFacts= new BufferedReader(new FileReader("foodfacts.csv"));
Scanner factFile = new Scanner(foodFacts);
List<String> facts = new ArrayList<String>();
// System.out.println("Printing out your array!");
while ( factFile.hasNextLine()){
fact = factFile.nextLine();
StringTokenizer st2 = new StringTokenizer(fact, ",") ;
while (st2.hasMoreElements()){
for ( int j = 0; j < NUM_COL ; j++) {
foodArray [numberOfLines][j]= st2.nextToken();
//System.out.println("Foodarray at " + " " + numberOfLines + " is " +foodArray[numberOfLines][j]);
}
}
numberOfLines++;
}
System.out.println("Please type in the food you wish to know about.");
String request; //user input
request = textIn.readLine();
System.out.println ("You requested" + request);
问题从这里开始!
for ( int i = 0; i < NUM_ROW ; i++)
{
if ( foodArray[i][0] == request)
for ( int j = 0 ; j < NUM_COL ; j++ )
System.out.println ( foodArray[i][j] ); //never prints anything
}
}
catch (IOException e)
{
System.out.println ("Error, problem reading text file!");
e.printStackTrace();
}
}
}
我正在尝试在foodArray [6] [0]匹配输入All-Bran Cereal的终端中测试它
答案 0 :(得分:2)
在上一个for
循环中,您使用==
中的if construct
运算符比较字符串,这会给您不正确的结果,因为==
会比较字符串引用,这将是不同的,因为两个引用都指向不同的字符串对象。
使用equals
方法比较字符串内容: -
if (foodArray[i][0].equals(request))
如果您想比较他们的equals
,则应始终对object
content
使用{{1}}方法。
查看此信息: - How do I Compare strings in Java了解详情。