how to take user input in Array using java?

前端 未结 8 1665
你的背包
你的背包 2020-12-03 12:35

how to take user input in Array using Java? i.e we are not initializing it by ourself in our program but the user is going to give its value.. please guide!!

相关标签:
8条回答
  • 2020-12-03 13:19

    Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).

    import java.util.*;
    
    public class UserInput {
        public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            Scanner stdin = new Scanner(System.in);
    
            do {
                System.out.println("Current list is " + list);
                System.out.println("Add more? (y/n)");
                if (stdin.next().startsWith("y")) {
                    System.out.println("Enter : ");
                    list.add(stdin.next());
                } else {
                    break;
                }
            } while (true);
            stdin.close();
            System.out.println("List is " + list);
            String[] arr = list.toArray(new String[0]);
            System.out.println("Array is " + Arrays.toString(arr));
        }
    }
    

    See also:

    • Why is it preferred to use Lists instead of Arrays in Java?
    • Fill a array with List data
    0 讨论(0)
  • 2020-12-03 13:26

    **How to accept array by user Input

    Answer:-

    import java.io.*;
    
    import java.lang.*;
    
    class Reverse1  {
    
       public static void main(String args[]) throws IOException {
    
         int a[]=new int[25];
    
         int num=0,i=0;
    
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    
         System.out.println("Enter the Number of element");
    
         num=Integer.parseInt(br.readLine());
    
         System.out.println("Enter the array");
    
         for(i=1;i<=num;i++) {
            a[i]=Integer.parseInt(br.readLine());
         }
    
         for(i=num;i>=1;i--) {
            System.out.println(a[i]);    
         }
    
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题