【问题标题】:Finding the total value for elements in a String [closed]查找字符串中元素的总值[关闭]
【发布时间】:2014-10-20 19:06:24
【问题描述】:

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

当我尝试使用 StringTokenizer 时遇到了问题,所以我使用了 split() 方法,但总金额减少了 7 或 28,具体取决于我使用的是 (i + i) 还是 (+= i) 在第二个 for 循环中。

// 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 [I@10ad1355. 

    /*
    // 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

【问题讨论】:

  • 你在sum添加什么?我认为你的程序有一个严重的错字。
  • 你不想sum += j吗?
  • @ ajb - 你是对的。不敢相信我没有看到。 @ Ben - 是的,我的意思是使用 sum += j 而不是 i。一旦我改变了它,它就可以正常工作了。

标签: java arrays split stringtokenizer


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    由于您已经在使用Scanner,您可以使用useDelimiter 方法为您拆分逗号。

    Scanner 也有一个nextInt() 来为你做从 String 到 int 的解析/转换

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

    【讨论】:

      【解决方案3】:

      我建议您使用\\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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-10
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 2020-10-19
        相关资源
        最近更新 更多