Splitting String and put it on int array

后端 未结 8 1392
眼角桃花
眼角桃花 2020-11-28 14:03

I have to input a string with numbers ex: 1,2,3,4,5. That\'s a sample of the input, then I have to put that in an array of INT so I can sort it but is not working the way it

8条回答
  •  醉梦人生
    2020-11-28 14:35

    Change the order in which you are doing things just a bit. You seem to be dividing by 2 for no particular reason at all.

    While your application does not guarantee an input string of semi colon delimited variables you could easily make it do so:

    package com;
    
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            // Good practice to initialize before use
            Scanner keyboard = new Scanner(System.in);
            String input = "";
            // it's also a good idea to prompt the user as to what is going on
            keyboardScanner : for (;;) {
                input = keyboard.next();
                if (input.indexOf(",") >= 0) { // Realistically we would want to use a regex to ensure [0-9],...etc groupings 
                    break keyboardScanner;  // break out of the loop
                } else { 
                    keyboard = new Scanner(System.in);
                    continue keyboardScanner; // recreate the scanner in the event we have to start over, just some cleanup
                }
            }
    
            String strarray[] = input.split(","); // move this up here      
            int intarray[] = new int[strarray.length];
    
            int count = 0; // Declare variables when they are needed not at the top of methods as there is no reason to allocate memory before it is ready to be used
            for (count = 0; count < intarray.length; count++) {
                intarray[count] = Integer.parseInt(strarray[count]);
            }
    
            for (int s : intarray) {
                System.out.println(s);
            }
        }
    }
    

提交回复
热议问题