简体   繁体   中英

How to get the the number of values from a user input string in java?

I want to do a bubble sort of numbers input by the user without asking the user how many numbers he wants to enter. User can enter as many numbers he can and the program should sort them all. So I want to find the number elements in the input before start sorting them. Here is the working code with user enter the array size himself

Update: it is one string of multiple integers eg "4 87 32 112 7" output I want is "4 7 32 87 112"(Ascending order)

import java.util.Scanner;
public class ArraySorting{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println("Enter size of the array");
int z=in.nextInt();
int a[]=new int[z];
System.out.println("Enter numbers");
for(int i=0;i<z;i++){
a[i]=in.nextInt();
}
for(int j=0;j<z-1;j++){
for(int p=0;p<(z-1)-j;p++){
if(a[p]>a[p+1]){
int n=a[p];
a[p]=a[p+1];  
a[p+1]=n;
}//if loop
}//for loop 2
}//for loop 1
System.out.println("Numbers in Ascending order:");
for(int k=0;k<z;k++){
System.out.print(a[k]+" ");
}
}
}

You can convert string sentence in to integer that can be Integer Value input for bubble sort.

import java.util.Scanner;

public class Sorting {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner reader = new Scanner(System.in);

    System.out.print("Enter the strings > ");
    String s1 = new String(reader.nextLine());

    String[] str = s1.split(" ");

    for(int i=1;i<str.length;i++){

        System.out.println(Integer.parseInt(str[i]));
    }
}

}

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