0

I'm doing a Java activity that prints the Numbers the user Input, and here's my codes:

System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int x = 1; x<=num1;x++){
    for (int i = 0 ; i<num1;){
        System.out.print("Enter Value #" + x++ +":");
        int ctr1 =Integer.parseInt(in.readLine());
        i++;
    }
}

How can I print all the input numbers? Here's the result of my code:

Enter How Many Inputs: 5
Enter Value #1:22
Enter Value #2:1
Enter Value #3:3
Enter Value #4:5
Enter Value #5:6

How can I print all this numbers as array. 22,1,3,5,6

1
  • You should probably use Scanner rather than BufferedReader, since it exposes nextInt. Anyways, there's plenty of ways to do this... do you actually want to build an array of the values? Commented Sep 29, 2012 at 15:44

2 Answers 2

1

Create an int[] array of length num. On every iteration take the user input and put it in the array at their specified index and break out of the while loop. and at last print the array elements by iterating over it.

    Scanner scan = new Scanner(System.in);
        System.out.println("enter num of values: ");
        int [] arr = new int[scan.nextInt()];
        for(int i=0;i<arr.length; i++) {
            scan = new Scanner(System.in);
            System.out.println("please enter a value: ");
            while(scan.hasNextInt()){
            int x = scan.nextInt()
                    ;
            arr[i]= x;
            break;
            }

        }
        for(int i:arr){
            System.out.print(i);
        }

OUTPUT: enter num of values: 5 please enter a value: 22 please enter a value: 2 please enter a value: 3 please enter a value: 5 please enter a value: 6 22 2 3 5 6

Sign up to request clarification or add additional context in comments.

Comments

0
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
int arr[] = new int[num1];

for (int i = 0; i<num1; i++)
{
    System.out.print("Enter Value #" + (i + 1) + ":");
    arr[i] =Integer.parseInt(in.readLine());
}

I guess this should do it... NOT TESTED


PRINTING

for(int i = 0; i < arr.length; i++)
    System.out.println(arr[i]);

SORTING

import java.util.Arrays;

Inside the code block

Arrays.sort(arr);

5 Comments

sorry still confuse how can i print all entered Numbers? thanks
Sir last question how can i display the entered numbers in ascending order.? thanks !
import java.util.Arrays; Then you can use Arrays.sort(arr); @WewDiocampo
gotcha , now i dont have any idea in descending order : (
@WewDiocampo It's your time now to do some research :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.