小编use*_*331的帖子

拆分String并将其放在int数组中

我必须输入一个带有数字ex:1,2,3,4,5的字符串.这是输入的一个示例,然后我必须将它放在一个INT数组中,这样我就可以对它进行排序,但它的工作方式不同.

package array;

import java.util.Scanner;

public class Array {

    public static void main(String[] args) {
        String input;
        int length, count, size;
        Scanner keyboard = new Scanner(System.in);
        input = keyboard.next();
        length = input.length();
        size = length / 2;
        int intarray[] = new int[size];
        String strarray[] = new String[size];
        strarray = input.split(",");

        for (count = 0; count < intarray.length ; count++) {
            intarray[count] = Integer.parseInt(strarray[count]);
        }

        for (int s : intarray) {
            System.out.println(s);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

java arrays string int

26
推荐指数
2
解决办法
11万
查看次数

读取字符串next()和nextLine()Java

问题是当我尝试拆分(.split"")每个空格时,我无法读取带有next()的变量输入,然后数组只得到我输入的前两个单词,所以我不得不使用keyboard.nextLine()和分裂过程的工作方式应该工作,我得到数组中的所有单词,但问题是,如果我使用nextLine()然后我必须创建另一个键盘对象来读取第一个变量(答案),这是唯一的方法我可以让它在这里工作是代码

    Scanner keyboard=new Scanner(System.in);
    Scanner keyboard2=new Scanner(System.in);//just to make answer word

    int answer=keyboard.nextInt();//if I don't use the keyboard2 here then the program will not work as it should work, but if I use next() instead of nextLine down there this will not be a problem but then the splitting part is a problem(this variable counts number of lines the program will have).

    int current=1;
    int left=0,right=0,forward=0,back=0;

    for(int count=0;count<answer;count++,current++)
    {
        String input=keyboard.nextLine();
        String array[]=input.split(" ");
        for (int counter=0;counter<array.length;counter++)
        {
            if (array[counter].equalsIgnoreCase("left")) …
Run Code Online (Sandbox Code Playgroud)

java string split next

1
推荐指数
1
解决办法
4万
查看次数

标签 统计

java ×2

string ×2

arrays ×1

int ×1

next ×1

split ×1