2016-12-14 67 views
0

我在一个while循环中创建了一个名为'S'的数组。找不到变量'S'。麻烦使用循环数组。

我已经在输入文件中逐行写入我的类;然后我设法得到每一行的第一个数字并将这些数字实现为一个字符串数组。

去我的while循环之外,我想用数组'S'来比较第一个元素和下两个元素,看他们是否匹配。

public static void main(String[] args) throws IOException{ 
     int count = 0; 
     FileReader Input = new FileReader("Input File"); 
     BufferedReader br = new BufferedReader(Input); 
     String line; 
     while((line = br.readLine()) !=null) 
     { 
      //System.out.println(line); 
      String[]bits = line.split(" +"); 
      String temp; 
      temp = bits[1].substring(0,1); 
      // System.out.println(temp); 
      String S[] = temp.split(" "); 
      //System.out.println(Arrays.toString(S)); 
     } 
     for(int i = 0; i < S.length; i++){ 
      if(S[i] == S[i + 1] && S[i] == S[i + 2]){ 
       count++; 
     } 
      System.out.println(count); 

我知道我的编码是可怕的。这是代码拼图第3天的问题。

回答

0

因为您在'while'循环中声明'S'之内,它只存在于while循环的上下文中。要在该循环外提供'S',请在之前声明循环:

String[] S = null; // Declare it here and initialize it with a "dummy" value. 
while((line = br.readLine()) !=null) 
{ 
    : 
    S[] = temp.split(" "); // Assign the "real" value. 
    : 
} 
// Now S will still be available for the rest of your method.