好吧,我将显示我的代码以及我的输入和输出,这非常奇怪我的数组的值似乎从一行变为下一行。
import java.io.*;
class chefAndNewRecipe
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new FileReader("/home/jer/Documents/chef.txt"));
int testCases = Integer.parseInt(r.readLine());
int numGuesses =0 ;
for (int i=0; i<testCases; i++)
{
int ingredients = Integer.parseInt(r.readLine());
String quantity = r.readLine();
String arr[] = quantity.split(" ");
int[] numIngredients = new int[arr.length];
for (int j =0; j< ingredients; j++)
{
String temp = arr[i];
numIngredients[i] = Integer.parseInt(temp);
System.out.println("This is numIngredients index: " + j + " and value " +numIngredients[i]);//print array location and value
}
System.out.println("numIngredients[0]:" + numIngredients[0]); // should be 2 and is
System.out.println("numIngredients[1]:" + numIngredients[1]); // should be 2 and is 0??
for (int k = 0; k< numIngredients.length; k++)
{
if (numIngredients[k] <2)
{
System.out.println("Value of numIngredients[k]: " + numIngredients[k]);// print value of numIngredients
System.out.println("-1");
}
else
{
numGuesses += numIngredients[k];
}
}
System.out.println(numGuesses);
}
}
}
我的输入是:
2
2
2 2
1
6
我的输出是:
这是数字索引:0和值2
这是数字索引:1和值2
数字[0]:2
数字[1]:0
数字的值[k]:0
-1
2
成分:1
数字的值[1]从2从一行变为另一行,我不了解发生了什么。
使用长变量名称即使对于循环变量也很有用 - 您似乎正在使用i
而不是j
:
for (int j = 0; j < arr.length; j++) // <== possibly arr.length is what you need.
{
String temp = arr[j]; // <=== was i, same next line
numIngredients[j] = Integer.parseInt(temp);
System.out.println(
"This is numIngredients index: " + j + //<== j this line
" and value " + numIngredients[j]); // <== again, was using [i]
}
使用currentIngredient
代替j
可能有助于找到错误。