Reputation: 87
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));
}
}
Upvotes: 0
Views: 276
Reputation: 122
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);
}
Upvotes: 1
Reputation: 1435
Try this
import java.util.Scanner;
public class A{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter Size : ");
int Size=Integer.parseInt(s.nextLine());
int array[] =new int[Size];
for(int i=0;i<array.length;i++){
System.out.print("Enter Number : ");
array[i]=Integer.parseInt(s.nextLine());
}
System.out.print("\narray : ");
for(int x:array)
System.out.print(x+" ");
}
}
and don't create new instance of a scanner each time. you can easily reuse it
Upvotes: 0
Reputation: 31
You don't need a loop to create the array just construct a new array with the required size like so:
int[] array = new int[ListaLength];
Upvotes: 0