I wrote the code below to get a sequence of integers as input and, split them into 2 parts based on a position number k
which is given by the user. Numbers larger than the specified number will be added to a list, and the others to another list.
Here'when i run program Variable nums might not have been initialized
compile time error is displayed. Can anyone give a solution.
(As i'm a beginner, i run java programs in Command Prompt)
If you are giving an alternative, please explain why this is happening.
import java.util.*;
import java.util.Scanner;
class StringSplit{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
List<Integer> part1=new ArrayList<Integer>();
List<Integer> part2=new ArrayList<Integer>();
int k,point=0;
int nums[]; //Declaring variable
System.out.print("\nEnter the point of split : ");
k=input.nextInt();
boolean correct=false;
String numbers;
System.out.print("\nEnter the number list : ");
numbers=input.nextLine();
String numlist[]=numbers.split(" ");
nums=new int[numlist.length]; //Declaring the size
for(int i=0;i<numlist.length;i++){
nums[i]=Integer.parseInt(numlist[i]); //Assigning values to the array
}
point=nums[k-1];
for(int x=0;x<nums.length-1;x++){
if(nums[x]>point) part1.add(nums[x]);
else part2.add(nums[x]);
}
System.out.print("\nPart 1 : ");
for(int i:part1){
System.out.print(" "+i);
}
System.out.print("\nPart 2 : ");
for(int j:part2){
System.out.print(" "+j);
}
}
}