如何在用户输入Java时拆分提供的字符串?

时间:2018-09-16 16:08:47

标签: java arrays sorting input split

如何分割用户提供的typecar中的color

输入格式为:

<Type>#<Color>

输出将显示多少辆color相同的汽车

输入示例:

how many cars : 10
sedan#red
truck#yellow
van#white
suv#black
sedan#black
roadster#red
suv#gray
coupe#gray
minivan#white
truck#red

输出必须按字母顺序排序

black 2
gray 2
red 3
white 2
yellow 1

尝试了一个示例代码,但仍未完成,但是在如何拆分数组T^T上遇到了困难

Class1

 public class Class1 {

    private String type ;
    private String color;
    private String format;

    public Class1() {
        this.type = "";
        this.color = "";
        this.format = "";
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public void split () {  
        String part[] = format.split("#");
        setType(part[0]);
        setColor(part[1]); // i don't know if this will work or not.. 
    } 
}

Class2

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Class2 {


    public static void main(String[] args) throws NumberFormatException, IOException {
        // TODO Auto-generated method stub
        int n ;
        String format ;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = Integer.parseInt(br.readLine());

        Class1 [] dataArray = new Class1[n] ;
        Class1 data = new Class1();

        for(int a = 0 ; a <= dataArray.length ; a++) {
            dataArray[a] = data;
            data.setFormat(br.readLine());

            data.split();
            data.getType();
            data.getColor();
        }
    }
}

编码仍未完成,并且仍然不知道如何拆分数组。请帮我解决这个问题!

3 个答案:

答案 0 :(得分:0)

从此更改您的for循环:

   for(int a = 0 ; a <= dataArray.length ; a++) {
        dataArray[a] = data;
        data.setFormat(br.readLine());

        data.split();
        data.getType();
        data.getColor();
    }

对此:

    for(int a = 0 ; a < dataArray.length ; a++) {
        Class1 data = new Class1();
        dataArray[a] = data;
        data.setFormat(br.readLine());

        data.split();
        data.getType();
        data.getColor();
    }

两个重要的更改是:

  1. 您只能在a < dataArray.length时循环播放,否则 您将在ArrayIndexOutOfBoundsException时得到一个a == dataArray.length

  2. 每次阅读时都需要创建Class1的新实例     一行,并将其存储在a的位置dataArray

除此之外,看起来还不错。显然,您的设计中存在一些小问题-也许setFormat应该调用split,而不是需要单独调用? -但是您现在应该可以使用dataArray

遍历Map<String, Integer>并计算颜色了

答案 1 :(得分:0)

我将通过使用Scanner来存储用户输入的'n'行来调整您的输入。在这里,我们使用split("#")逐行解析输入。因此,现在汽车的类型存储在第一个索引中,颜色存储在第二个索引中。接下来,我们使用TreeMap存储值,其中key是颜色,value是计数。使用TreeMap是已排序的集合,因此您无需显式地对地图进行排序。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("how many cars :");
    int num_of_cars = sc.nextInt();
    sc.nextLine();
    String[] input;
    Map<String, Integer> mapCountColor = new TreeMap<>();

    System.out.println("Enter car#color");
    while (num_of_cars > 0) {
        // splitting the input and storing in the array
        input = sc.nextLine().split("#");

        if (mapCountColor.get(input[1]) != null) 
        {
           // check if key is already present in the map, if yes get the previous value and increment by 1
            mapCountColor.put(input[1], mapCountColor.get(input[1]) + 1);
        } 
        else 
        {  
           // not present then just add the key with default value 1
            mapCountColor.put(input[1], 1);
        }

        num_of_cars--;
    }
    mapCountColor.entrySet().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
}

答案 2 :(得分:0)

在for循环内而不是在其外部初始化新对象Class1 data = new Class1();,否则它将在每次循环运行时被覆盖。

也要遍历a < dataArray.length而不是a <= dataArray.length

我添加了groupingBy,以得到按颜色名称分组的计数。然后,我对结果entrySet中的Map<String, Integer>进行了排序,并打印出内容。

我已经实现了预期的输出,而无需过多修改您的代码。

public static void main(String[] args){
    try{
        int numberOfCars;
        String format ;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        numberOfCars = Integer.parseInt(br.readLine());
        Class1 [] dataArray = new Class1[numberOfCars] ;

        for(int a = 0 ; a < dataArray.length ; a++) {
            //Initializing new instance everytime
            Class1 data = new Class1();
            data.setFormat(br.readLine());
            data.split();
            dataArray[a] = data;
        }
        //Creating a Stream of Class1 objects
        Arrays.stream(dataArray)
              .collect(Collectors.groupingBy(car -> car.getColor(), Collectors.counting()))
              .entrySet() //Getting entries from Map
              .stream() //sorting after the Map is created to preserve the sorted order
              .sorted(Comparator.comparing(entry -> entry.getKey())) //Sorting by key, that is the Color property of Class1
              .forEach((entry) -> System.out.println(entry.getKey() + " "+ entry.getValue()));
        }catch (NumberFormatException | IOException | ArrayIndexOutOfBoundsException e) {
              System.out.println("Error occurred try again");
              e.printStackTrace();
        }
}