1

数组存储了所有的信息,感觉这个程序真的很接近工作了。我知道它不干净,我会马上清理它!问题在底部。

 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 匹配的终端中对其进行测试

4

1 回答 1

2

在您的最后一个for循环中,您正在使用==中的运算符比较您的字符串if construct,这会给您带来不正确==的结果,因为比较字符串引用,这将是不同的,因为两个引用都指向不同的字符串对象。

使用equals方法比较字符串内容:-

if (foodArray[i][0].equals(request))

如果您想比较它们equals的.objectcontent

Check out this post: - How do I Compare strings in Java for more details.

于 2012-11-14T18:44:50.460 回答