Java-Reading Mixed Data Types

Reading Mixed Data Types

You can use Scanner to read input that contains several different types of data—even if the order of that data is unknown in advance. You must simply check what type of data is available before reading it. When reading mixed data types, as the following program does, you need to be a bit careful about the order in which you call the next methods. For example, if the loop reversed the order of the calls to nextInt( ) and nextDouble( ), both numeric values would have been read as doubles, because nextDouble( ) matches any numeric string that can be represented as a double.



Program Source

import java.util.Scanner;

public class Javaapp {
    public static void main(String[] args) {
        String str = "10 TRUE JAVA 4.5 C++ 50";
        int i = 0;
        double d = 0;
        boolean b = false;
        String s;
        Scanner instr = new Scanner(str);
                i = instr.nextInt();
                System.out.println("Integer i = "+i);
            }else if(instr.hasNextDouble())
                d = instr.nextDouble();
                System.out.println("Double  d = "+d);
            }else if(instr.hasNextBoolean())
                b = instr.nextBoolean();
                System.out.println("Boolean b = "+b);
            }else if(instr.hasNext())
                s =;
                System.out.println("String  s = "+s);

Leave a Comment