Question:
How to read a string off the keyboard in the scanner class in Java?
Noah Smith
2010-12-22 20:56:53 UTC
Scanner reader = new Scanner(System.in)
I don't know if it was just the program I was using before or what but with the scanner class to read Ints it was reader.nextInt(); and doubles were reader.nextDouble(); which work fine in other programs but to read strings entered on the keyboard by the user, it was reader.nextLine(); is there another way to do it or was I doing something wrong? Because now when I use reader.nextLine(); it actually does just skip the current line and go to the next. I'm fairly confident that all the code was in order. Thanks!
Three answers:
Megatrone
2010-12-22 21:37:09 UTC
You can use Scanner to get input to your program. In the Scanner,

When input is INT type you must use

Int nu=reader.nextInt();

when its Double

Double val=reader.nextDouble();

when its String

String s=reader.nextLine();



Or



you can use IOSTREAM to get inputs. IOSTREAM is in Java.io package. This program will help you to understand it.



import java.io.*;

public class TestInputString{

public static void main(String[] arg)throws IOException{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please Enter Your Full name");

String s=br.readLine();

System.out.println("You Entered "+s);

}

}



******Note******

Buffered Reader get all input as String values. So if you want to Int or any other type of Input, you must use PARSER.

EG: If you want INT type input, you have to use INTPARSE

int Val=Integer.parseInt(br.readLine());
chandronnait
2016-11-11 01:39:46 UTC
Scanner Keyboard Java
auddrey_nw
2010-12-22 21:39:54 UTC
You can use

String myStr = input.next(); so .next() instead of .nextLine(). Here is an example



import java.util.Scanner;

public static void main(String args[])

{

Scanner input = new Scanner(System.in);

System.out.print("Enter TWO dates: ");

String myStr = "";;

String myStr2 = "";



while (input.hasNext())

{

myStr = input.next();

myStr2 = myStr2 + myStr;

}

input.close();

System.out.print("You entered:" + myStr2);

}

}



see similar example on

http://www.java2s.com/Code/Java/Development-Class/UseScannertoreaduserinput.htm


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...