Search code examples
javaarraysjcreator

Choosing an arrays size and populate it with user input


The user writes in how many numbers that is going to be in the array and then the user writes in the numbers himself. Im not sure on how to write the code for this.

(The numbers is not supposed to be generated. Sorry for the swedish words.).

The point of the code is to find a number that is in the array

import java.util.Scanner;
class Sok1 {

    public static void main (String[] args ) {

        System.out.println("Hur många nummer ska din lista bestå av?";
        int ListaLength = new Scanner(System.in).nextInt();
        for(int i=0; i<=ListaLength i++){
            int array
            array[i]=
            //This is where i am stuck.^^^^

        }
    } 

System.out.println("Skriv in ditt första nummer.");
int Lista1 = new Scanner(System.in).nextInt();
System.out.println("Skriv in ditt andra nummer.");
int Lista2 = new Scanner(System.in).nextInt();
System.out.println("Skriv in ditt tredje nummer.");
int Lista3 = new Scanner(System.in).nextInt();
System.out.println("Skriv in ditt fjärde nummer.");
int Lista4 = new Scanner(System.in).nextInt();
System.out.println("Skriv in ditt femte nummer.");
int Lista5 = new Scanner(System.in).nextInt();

//This is the part of code that i removed because the new code is replacing it



    System.out.println("Skriv in numret du letar efter.");
    int element = new Scanner(System.in).nextInt();
    System.out.println(" ");

    int[] myList = {Lista1,Lista2,Lista3,Lista4,Lista5};

    for (int i = 0; i < myList.length; i++) {
        System.out.println(myList[i] + " ");
    }

    for (int i = 0; i < myList.length; i++) {
        if (myList[i] == element)
            System.out.println ("Din siffra är på plats " +(i+1));
        }
    }

Solution

  • Try the below code to take the array size from user and then user input elements:

    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        System.out.println("Hur många nummer ska din lista bestå av?");
        int ListaLength = s.nextInt();
        Integer array[] = new Integer[ListaLength];
        for (int i = 0; i < ListaLength; i++) {     
            array[i] = s.nextInt();
    
        }
        for(int i : array){
            System.out.print(i+" ");
        }
        System.out.println("Skriv in numret du letar efter.");
        int num = s.nextInt();
        int index = Arrays.asList(array).indexOf(num);
        System.out.println(index);
    
    }