简体   繁体   中英

Having some problems with Array Lists and adding values. Java

I was working on this problem using arrays and array lists, and then I want to sort the array list to that the numbers the user enters are in ascending over. When I try to run this, I get two error codes, 1: the period on the list.add(num1); is not recognized, and then the other error code is that the Arrays.sort(list); is not recognized, I honestly have no clue what to do, I searched the web all over and could not find anything, this is the sole reason I made this account xD. Please help!!!

import java.util.Scanner;
import java.util.*;
import java.util.Arrays;

public class randomArrayList{
    public static void main(String[] args){
        int n = 5;
        ArrayList<Integer> list = new ArrayList<Integer>(n);
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter 5 numbers: ");
        int num1 = input.nextInt();
        list.add(num1);
        int num2 = input.nextInt();
        list.add(num2);
        int num3 = input.nextInt();
        list.add(num3);
        int num4 = input.nextInt();
        list.add(num5);
        int num5 = input.nextInt();
        list.add(num5);
        Arrays.sort(list);
        System.out.println(list);
    }
}

This is what you want

Note

can not add list.add(num5); before you have declared the variable. I think you want to add num4

and

Arrays.sort(list); as the name implies is for sorting Arrays.

use Collections.sort(list) instead

int n = 5;
ArrayList<Integer> list = new ArrayList<Integer>(n);
Scanner input = new Scanner(System.in);

System.out.println("Please enter 5 numbers: ");
int num1 = input.nextInt();
list.add(num1);
int num2 = input.nextInt();
list.add(num2);
int num3 = input.nextInt();
list.add(num3);
int num4 = input.nextInt();
list.add(num4);
int num5 = input.nextInt();
list.add(num5);
Collections.sort(list);
System.out.println(list);

Although a cleaner way would to be use a loop

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