package nizovi;
import java.util.Scanner;
public class Nizovi {
private static String array;
public static void main(String[] args) {
Scanner sc= new Scanner (System.in);
int k = sc.nextInt();
int[] pos =new int[k];
int[] neg = new int [k];
Scanner n= new Scanner (System.in);
System.out.println("Enter the number of members of array:");
int members = n.nextInt();
for (int i=k;i>0;){
Scanner numb= new Scanner (System.in);
System.out.println("Enter number:");
int num=numb.nextInt();
if (broj >=0){
pos[num]=n.nextInt();
}
else{
neg[num]=n.nextInt();
}
}
}
}
I am using for loop and I am confused how to add more numbers into it because if I leave array command in for loop it defines it every time with the different scanner.Sorry for the bad explanation.
First: use one Scanner
per input source, so here just one not 3
Then, you need to it by steps, you do a lot of useless things
k
k
times the user to input a valueBut you'll have zeros in your array, because you create 2 arrays of size k
but enter only k
elements, so you'll have k
zeros in total in your arrays, use List
to have only what you need
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of members of array:");
int k = scanner.nextInt();
int[] pos = new int[k];
int[] neg = new int[k];
for (int i = 0; i < k; i++) {
System.out.println("Enter a number:");
int numberUser = scanner.nextInt();
if (numberUser > 0) {
pos[i] = numberUser;
} else {
neg[i] = numberUser;
}
}
System.out.println(Arrays.toString(pos));
System.out.println(Arrays.toString(neg));
Scanner numb= new Scanner (System.in);
That statement... is simply useless.
You already defined a valid scanner once, further up, named n
.
You only should:
scannerForUserInput
instead of n
.There is simply no need to define a new scanner for each new input data.
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.