Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

String Input Using the Scanner Class

Later, when we cover the String class, there are methods such at charAt to hangle characters, but for now we use the scanner class

Note however that there is no method in the Scanner class to handle characters (only strings of length 1 which is a character)

Example 1

Example 2

 

 

Example 1

 

import java.util.Scanner;

public class StringInput

{

      public static void main(String[] args)  

      {

            Scanner in = new Scanner(System.in);      

                                                                                                      

            String str1;

            System.out.println("What is your first name?");

            str1 = in.next();

            System.out.println("Your first name is: " + str1);

      }

}

 


Output

 

What is your first name?
BeetleJuice
Your first name is: BeetleJuice

 

 

Characters  (note that the Scanner class does not have a nextChar method)

 

import java.util.*;

public class Characters

{

 

      public static void main(String[] args)

      {

            String input;

            Scanner in = new Scanner(System.in);

            input = in.nextLine();

            System.out.println("The character you entered is: " + input);

      }

}

 

OUTPUT

 

S

The character you entered is: S

 

 

Example 2

 

 

import java.util.Scanner;

 

class myClass

{

    public static void main(String[] args)

    {

        Scanner scn = new Scanner(System.in);

        double grade=0;

        String name;

        System.out.print("Please enter the grade: ");

        grade = scn.nextDouble(); //Could also be scn.next(), scn.nextInt(), and so on

       

        System.out.print("Please enter name: ");

        name = scn.next();

        System.out.println("Name: "+name+", grade: "+grade);

    }

}

 

OUTPUT

 

 

Please enter the grade: 98.7

Please enter name: Mohammad

Name: Mohammad, grade: 98.7