2016-05-12 35 views
-2

我是一个新手编码器,需要一些帮助。我试图根据与我可以使用多少位数相对应的数字将数字的数字相加。我使用Eclipse Juno并使用单独的文本文件来使用我的数字。虽然没有太多这是我现在有:用指引添加数字列表中的数字

public static void main(String[] args) throws IOException{ 

String token1 = ""; 
Scanner infile1 = new Scanner(new File("input.txt")); 
ArrayList<String> temps = new ArrayList<String>(); 
//Adding Input files to the Arraylist 
while(infile1.hasNext()){ 
    token1 = infile1.next(); 
     temps.add(token1);  
} 
infile1.close(); 
//Calling the Numbers from ArrrayList temps 
    for(int x = 0; x < temps.size(); x++) { 
System.out.println(x + " " + temps.get(x)); 
for(x = 0; x < temps.size(); x++){ 

} 
} 


    } 

} 

的数字是 9678415 7, 9678415 6, 9678415 5, 9678415 4, 2678515 3, 数量增加,位数使用。 input.txt文件没有逗号

+0

我忘了提及返回最高数字值 – LittleRising

+1

你想要做什么的描述不清楚。请显示输入的示例以及预期的输出。 – AdrianHHH

+0

示例输出应该是986541,987641,98765,9876和875 – LittleRising

回答

1

你究竟是怎么做的,将取决于数据在文件中的样子。你说它不是用逗号分隔的,所以我将不得不假设它们被行隔开。您将需要分离字符串中的值并将其转换为int;所以如果我理解了这个问题,下面应该做你正在尝试的东西。 (全面披露,它是一个小而自从我用Java编写的,我也没有办法,现在来测试这一权利,确保我没有作出任何基本的语法错误)

ArrayList<Integer> totalArray = ArrayList<Integer>(); 
for(String tStr : temps){ 
    int tempTotal = 0; 
    String[] numArray = tStr.split(" "); 
    for(int x = 0; x < Integer.parseInt(numArray[1]){ 
     int y = Integer.parseInt(numArray[0].substring(x,x+1)); 
     tempTotal += y; 
    } 
    totalArray.add(tempTotal); 
} 

有可能是获得最高价值的更好方法,但是由于我已经离开了一段时间,我只能以我能想到的最基本的方式去做。

int highestValue = 0; 
for (Integer x : totalArray){ 
    if(highestValue<=x){ 
     highestValue = x; 
    } 
} 
return highestValue; 
+0

P.S.我认为我在这个答案中使用的增强for循环仅在版本1.5和更高版本中可用。在这一点上,我们已经很好地了解了这一点,我想大多数系统都会使用比这更晚的版本,但是您认为您可能需要知道。 –