2016-02-20 76 views
0

在我开始讨论这个问题之前,让我先描述代码应该解决的问题。嵌套for循环中的字符串变量未得到修改

的代码应该在输入采取从文件中的语法如下:

1,2,3,4;5 

的代码应该采取的整数,它是分号后,并将其分配给一个变量,其中它不。然后代码应该采用分号前的值并查找并返回分号后加起来的所有两对整数。

实施例:如果输入是

1,2,3,4;5 

则输出应该是

1,4;3,2 

我是,我的String result没有被内嵌套for循环编辑的问题码。我没有得到编译时或运行时错误。它只是不编辑String result,我不明白为什么。你们可以看看吗?

import java.util.*; 
import java.io.*; 

public class NumberPairs2 { 
    public static void main (String[] args) throws IOException { 
     File file = new File("C:/Users/James/Desktop/txt.txt"); // Takes in a file as input 
     BufferedReader buffer = new BufferedReader(new FileReader(file)); 
     String line; 
     while ((line = buffer.readLine()) != null) { 
      String result = ""; // creates an empty string 
      line = line.trim(); // set the file contents equal to null 
      if (line.length() != 0){ 
       int sumTest = Integer.parseInt(line.substring(line.indexOf(";") + 1)); 
       String[] intArray = line.split(";"); 
       String[] intArray2 = intArray[0].split(","); 
       for (int i = 0; i < intArray2.length - 1; i++){ 
        for(int j = i + 1; i < intArray2.length; i++){ 
         if (intArray2[i] != "," && intArray2[j] != "," && Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){ 
          result += intArray[i] + ", " + intArray[j] + ";"; 
          System.out.println(result); 
         } 
        } 
       } 


       //int compare =() 

      } 
      else { 
       result = null; 
       System.out.println(result); 
      } 

     } 


    } 
} 
+0

我编辑了自己的问题。我试图将大段落分成更小的块,并使用正确的代码格式;我删除了很多“so”,并修复了代码缩进。 –

回答

0

您需要使用intArray2[i] & intArray2[j]增加result而不是intArray[i] & intArray[j]时。在尝试使用intArray中的intArray2索引时,您的代码当前正在获取ArrayIndexOutOfBoundsException

for (int i = 0; i < intArray2.length - 1; i++){ 
    for(int j = i + 1; j < intArray2.length; j++){ 
     if (Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){ 
      result += intArray2[i] + ", " + intArray2[j] + ";"; 
      System.out.println(result); 
     } 
    } 
} 

一个选项去掉最后一个分号将追加到如下结果

//if not 1st pair, add semicolon 
if(!result.equals("")){ 
    result += "; "; 
} 
result += intArray2[i] + ", " + intArray2[j]; 
+0

我做了你的改变,增加j和我比较是一个错误,我并不是故意放在那里,但我修复了你说的一切,结果仍然没有被编辑 – Shiloh

+0

嗯...你试过'result = result + .. 。'?我很确定'+ ='应该可以工作,但是我没有看到其他任何看起来错误的东西。 –

+0

那也不管用。这个litteraly没有意义 – Shiloh

0

这可能有助于

for (int i = 0; i < intArray2.length - 1; i++){ 
     for(int j = i + 1; j < intArray2.length; j++){ 
     if (Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){ 
      result += intArray2[i] + ", " + intArray2[j] + ";"; 
      } 
     } 
} 
System.out.println(result); 
+0

确定它在CodeEval中工作,但不是我的编辑器出于某种原因...肯定是在ym方面的一个问题。好吧,我试图弄清楚如何在数字之间保留分号,但在最后丢弃这个分号。我试过System.out.println(result.substring(0,result.length() - 1)));但我有一个索引超出界限例外。有任何想法吗? – Shiloh

+0

result = result.replaceAll(“\\; $”,“”); – Bhushan