简体   繁体   English

Java数组-将带空格的字符串转换为数组

[英]Java Arrays- transforming string with spaces into an array

public class MatrixMultiply{

    public static void main(String[] args) {
        main();
    }


    static void main() {
        int[] vec = { 1, 2, 3, 4, 5 };
        System.out.println( mean( vec ) );
    }

    static int mean(int[] v) {
        int total = 0;

        for (int i = 0 ; i < v.length ; i++ ) {
            total = total + v[i];
        }
        return total / v.length;
    }
}

The above works but i don't want to say "int[] vec = { 1, 2, 3, 4, 5 };" 上面的作品,但我不想说“ int [] vec = {1,2,3,4,5};” I want to create something like: 我想创建类似的东西:

String w = "1 2 3 4 5"; 

and then work out the mean of w. 然后算出w的平均值。 How would i be able to get to w and do this? 我将如何去做这件事?

If you are sure that the numbers are separated by whitespaces, i guess you should use foreach with w.split(" "); 如果您确定数字之间用空格隔开,我想您应该在w.split(“”);中使用foreach; and Integer.parseInt(); 和Integer.parseInt(); like this: 像这样:

double sum=0;

for(String str : w.split(" ")) {
    sum += Integer.parseInt(str);
}

return sum / w.split(" ").length;

Edit: replaced int sum with double sum, to keep actual results with fractions, not only integer part. 编辑:用双和代替int sum,以分数保留实际结果,而不仅仅是整数部分。

Take a lookat java.util.Scanner. 查看一下java.util.Scanner。

Something like (not tested, just off the top of my head): 像这样的东西(未经测试,就在我的头顶):

Scanner scanner;

scanner = new Scanner("1 2 3 4 5 6");

while(scanner.hasNextInt())
{
    final int x;

    x = scanner.nextInt();
    total += x;
}

For your program I'd do: 对于您的程序,我愿意:

import java.util.ArrayList; 导入java.util.ArrayList; import java.util.List; 导入java.util.List; import java.util.Scanner; 导入java.util.Scanner;

public class Main { public static void main(final String[] argv) { final int[] vec; 公共类Main {公共静态void main(final String [] argv){final int [] vec; final float meanValue; 最终浮点均值;

    vec       = toIntArray("1 2 3 4 5 6");
    meanValue = mean(vec);

    System.out.println("mean = " + meanValue);
}

private static float mean(final int[] vec)
{
    int total = 0;

    for(final int val : vec)
    {
        total += val;
    }

    return ((float)total) / ((float)vec.length);
}


private static int[] toIntArray(final String value)
{
    final Scanner       scanner;
    final List<Integer> list;
    final int[]         vec;

    scanner = new Scanner(value);
    list    = new ArrayList<Integer>();

    while(scanner.hasNextInt())
    {
        final int val;

        val = scanner.nextInt();
        list.add(val);
    }

    vec = new int[list.size()];

    for(int i = 0; i < list.size(); i++)
    {
        vec[i] = list.get(i);
    }

    return (vec);
}

} }

You could use Java's StringTokenizer -- class to get the individual tokens and then the Integer class to treat them as integers. 您可以使用Java的 StringTokenizer-类来获取单个令牌,然后使用 Integer类将它们视为整数。

Sorry, use the .split instead. 抱歉,请改用.split

From the API docs: 从API文档:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
string.split(" ").map(_.toInt) sum

Oh sorry, that's Scala. 哦,抱歉,这是Scala。 Have some Java! 有一些Java!

String[] arr = string.split(" ")
int sum = 0;
for (s : arr) sum += Integer.parseInt(s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM