简体   繁体   中英

Integer.parseInt : Java ERROR in Bubble Sorting

I'm having this error multiple times. How to fix it.. I have solved it without command line arguments but now this is giving me an error. How to solve it with Integer.parseInt() .

 BubbleSort.java:24: error: incompatible types: String[] cannot be converted to String int num[] = Integer.parseInt(args); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error 
 class  Demo { 
     static void bubble(int[] list) {  
       int temp = 0, k , j;
       int n = list.length;
       for(k = 0;k < n - 1;k++) {
        for(j = 0;j < n - k - 1;j++) { 
         if(list[j] > list[j + 1]) {
          temp = list[j];
          list[j] = list[j + 1];
          list[j + 1] = temp;
         }
        }
       }
      } 

     public static void main (String[] args) {
      int len=args.length;
      int num[] = Integer.parseInt(args);
      bubble(num);
      for(int i = 0;i < len; i++) {
       System.out.println("Array after bubble sort :" +args[i]);
       }
      }
    }  

The line

int num[] = Integer.parseInt(args);

is wrong. Look at the error message, it clearly indicates this error: parseInt(...) does not take a string array but a single string instead. Replace the line with this:

int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
    num[i] = Integer.parseInt(args[i]);
}

Try this:

int num[];
for (int i = 0; i < len; i++) {
    num[i] = Integer.parseInt(args[i]);
}

instead of:

int num[] = Integer.parseInt(args);

This is because args variable is an array of strings and the Integer.parseInt method take a single string as argument, not an array.

args is not a single String. Its an array of Strings. You can use the following code to parse the String array args into an integer array:

int[] num= Arrays.stream(args)
        .mapToInt(Integer::parseInt)
        .toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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