2014-10-20 18 views
-2

我的挑战是通过用户输入查找字符串内元素的总值。 用户输入应该如下:1,2,3,4,5,6,7 ...查找字符串中元素的总值

我遇到问题,当我试图使用StringTokenizer,所以我去了split()方法但根据我在第二个for循环中使用(i + i)还是(+ = i),总金额将减少7或28。

// Libraries 
import java.util.Scanner; 
import java.util.StringTokenizer; 

public class Project_09_8 
{ 

    public static void main(String[] args) 
    { 

    // Create instance of Scanner class 
    Scanner kb = new Scanner(System.in); 

    // Variables 
    String input;      // Holds user input 
    String [] result;     // Holds input tokens in an array 
    int i = 0;       // Counter for loop control 

    // User input 
    System.out.print("Please enter a positive whole number, separated by commas: "); 
    input = kb.nextLine(); 
    result = input.split(","); 

    // Converts input String Array to Int Array 
    int [] numbers = new int [result.length];     

    // Loop through input to obtain each substring 
    for (String str: result) { 
     numbers[i] = Integer.parseInt(str); 
     i++; 
    } 

    // Receive this output when printing to console after above for loop [[email protected] 

    /* 
    // Loop to determine total of int array 
    int sum = 0;      // Loop control variable 
    for (int j : numbers) { 
     sum += i; 
     //sum = i + i;     
    } 

    // Print output to screen 
    System.out.println("\nThe total for the numbers you entered is: " + sum); 
    */ 

    } // End main method 

} // End class 
+0

什么要补充到'sum'?我认为你的程序有一个重大的错字。 – ajb 2014-10-20 19:09:37

+3

你不想要'sum + = j'? – Ben 2014-10-20 19:09:55

+0

@ ajb - 你是对的。不敢相信我没有看到。 @ Ben - 是的,我打算使用sum + = j而不是i。一旦我改变它,它的工作正确。 – ml24 2014-10-20 19:12:02

回答

0

我建议你上(可选)空格分割与\\s*,\\s*,当你需要他们,并在一个循环中添加的总和(不转换成int[]副本),如声明变量,

public static void main(String[] args) { 
    // Create instance of Scanner class 
    Scanner kb = new Scanner(System.in); 
    System.out.print("Please enter a positive whole number, " 
     + "separated by commas: "); 
    String input = kb.nextLine(); 
    String[] result = input.split("\\s*,\\s*"); 
    int sum = 0; 
    for (String str : result) { 
     sum += Integer.parseInt(str); 
    } 
    System.out.println(Arrays.toString(result)); 
    System.out.printf("The sum is %d.%n", sum); 
} 
2

Java 8,你可以把自己摆脱苦难

代码:

String s = "1,2,3,4,5,6,7"; 
String[] sp = s.split(","); 
//Stream class accept array like Stream.of(array) 
// convert all String elements to integer type by using map 
// add all elements to derive summation by using reduce 
int sum = Stream.of(sp) 
       .map(i -> Integer.parseInt(i)) 
       .reduce(0, (a,b) -> a+b); 
System.out.println(sum); 

输出:

28 
1

既然你已经使用Scanner可以使用useDelimiter方法拆分的逗号你。

扫描仪还具有nextInt()做解析/从字符串转换为int你

Scanner s = new Scanner(System.in) 
        .useDelimiter("\\s*,\\s*"); 
    int sum = 0; 
    while(s.hasNextInt()){ 
     sum += s.nextInt(); 
    } 
    System.out.println(sum);