• Register
140 points
4

In this article, you will learn about the scanner class of how to read and use the string array with a relatable example. Just check out the basics of scanner class, its syntax, and the scanner methods for your reference.

Scanner Class

It is one of the pre-defined class used to take values at run-time. This pre-defined class is available in util package. So one must definitely import this package before using a scanner class. While the packages is a collection of classes, interfaces and sub-packages which are grouped into a single unit. 

It is known that every package should be pre-fixed by keyword import.

Syntax

import java.util.Scanner;

Scanner obj = new Scanner(System.in)

Scanner Methods

The below table explains about the method name and its use

1. nextInt() -> Returns the next integer value

2. nextDouble() -> Returns the next double value

3. nextFloat() -> Returns the next Float value

4. nextLong() -> Returns the next long value

5. nextShort() -> Returns the next short value 

6. next() -> Returns the next one word string value

7. nextLine -> Returns the next multiplr word string value

how to take string array input in java using scanner - Program

import java.util.Scanner;

public class StringArrayDemo

{

public static void main(String[] args)

 {
    
Scanner sc=new Scanner(System.in);
    
System.out.println("enter the length of String array");
    
int n=sc.nextInt();
    
String[] sarray=new String[n];

for(int i=0;i<n;i++)

{
        
System.out.println("enter the "+(i+1)+" String :");
      
  sarray[i]=sc.next();
 
 }
    
System.out.println("Strings Entered by user:");

  for(String s:sarray)

{
        
System.out.println(s);

}

}

}
enter the length of String array

3

Enter the 1 string : coding

Enter the 2 String : with

Enter the 3 String : kodlogs

Strings entered by user : 

Coding with kodlogs
140 points
4