This question already has answers here:
System.console() returns null
(13 answers)
Closed 7 years ago.
I want to input a name and to print the first char ....
public class Test {
public static void main(String[] args) {
Console console = System.console();
System.out.println("Type your name : ");
String inputChar = console.readLine();
char firstChar = inputChar.charAt(0);
System.out.println(firstChar);
}
}
Some IDEs will return NPE for Console class. you can use the Scanner class and do it easily:
try this:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Name:");
String s = scan.next();
System.out.println(s.charAt(0));
this will print the first letter of your input String.
Using the Console class can a bit unreliable at times.
For reading console input, it would be preferrable to use either the Scanner class or a BufferedReader.
You can use a Scanner like :
Scanner scanner = new Scanner(System.in); // System.in is the console's inputstream
System.out.print("Enter text : ");
String input = scanner.nextLine();
// ^^ This reads the entire line. Use this if you expect spaces in your input
// Otherwise, you can use scanner.next() if you only want to read the next token
System.out.println(input);
You can also use BufferedReader like :
pre Java 7 syntax
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
Java 7 syntax
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
} catch (Exception e) {
e.printStackTrace();
}
Note: You need to use a try-catch statement when calling br.readLine() because it throws an IOException.
You can use Scanner if you want to read tokens (chunks of text separated by spaces). Use a BufferedReader if you want to simply read from the InputStream.
Related
I'd like to read the "text8" corpus in Java and reformat some words. The problem is, in this 100MB corpus all words are on one line. So if I try to load it with BufferedReader and readLine, it takes away too much space at once and can't handle it to separate all the words in one list/array.
So my question: Is it possible in Java to read instead of line by line a corpus, to read it word by word? So for example because all words are on one line, to read for example 100 words per iteration?
you can try using Scanner and set the delimiter to whatever suits you:
Scanner input=new Scanner(myFile);
input.useDelimiter(" +"); //delimitor is one or more spaces
while(input.hasNext()){
System.out.println(input.next());
}
I would suggest you to use the "Character stream" with FileReader
Here is the example code from http://www.tutorialspoint.com/java/java_files_io.htm
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
It reads 16 bit Unicode characters. This way it doesnt matter if your text is in one whole line.
Since you're trying to search word by word, you can easy read till you stumble upon a space and there's your word.
Use the next method of java.util.Scanner
The next method finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of Scanner.hasNext returned true.
Example:
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String a = sc.next();
String b = sc.next();
System.out.println("First Word: "+a);
System.out.println("Second Word: "+b);
sc.close();
}
Input :
Hello Stackoverflow
Output :
First Word: Hello
Second Word: Stackoverflow
In your case use Scanner for reading the file and then use scannerobject.next() method for reading each token(word)
try(FileInputStream fis = new FileInputStream("Example.docx")) {
ZipSecureFile.setMinInflateRatio(0.009);
XWPFDocument file = new XWPFDocument(OPCPackage.open(fis));
ext = new XWPFWordExtractor(file);
Scanner scanner = new Scanner(ext.getText());
while(scanner.hasNextLine()) {
String[] value = scanner.nextLine().split(" ");
for(String v:value) {
System.out.println(v);
}
}
}catch(Exception e) {
System.out.println(e);
}
I have declared two strings and reading the input using Scanner(System.in).
After this when i am closing the Scanner and again reading the another input using the Scanner,then it throws an error: NoSuchElementException.
Please guide me on this
import java.util.Scanner;
import java.io.*;
public class NumericInput
{
public static void main(String[] args)
{
// Declarations
Scanner in = new Scanner(System.in);
String string1;
String string2;
// Prompts
System.out.println("Enter the value of the First String .");
// Read in values
string1 = in.nextLine();
// When i am commenting below line(in.close) code is working properly.
in.close();
Scanner sc = new Scanner(System.in);
System.out.println("Now enter another value.");
string2 = sc.next();
sc.close();
System.out.println("Here is what you entered: ");
System.out.println(string1 + " and " + string2);
}
}
When you close your scanner it also closes System.in input stream, you are using it again, but it's closed, so when you try to use Scanner again, no open System.in stream is found.
There is no need to close a Scanner, since it implements AutoCloseable interface you should declare resources in try-with-resources as of java 7. If closing Scanner is an issue.
try(Scanner in = new Scanner(System.in); Scanner sc = new Scanner(System.in)){
// do stuff here without closing
}
catch(Exception){
e.printStackTrace();
}
This question already has answers here:
System.in.read() method
(6 answers)
Closed 8 years ago.
I use this official example to receive input from the user and then print it:
import java.io.IOException;
public class MainClass {
public static void main(String[] args) {
int inChar;
System.out.println("Enter a Character:");
try {
inChar = System.in.read();
System.out.print("You entered ");
System.out.println(inChar);
}
catch (IOException e){
System.out.println("Error reading from user");
}
}
}
The problem, It always returns incorrect values. For example, When enter 10 it returns 49 while I expect to return 10!
What is the reason for this issue and how could I solve it.
This returns the int value of a character, if you want to print the character cast it to char:
System.out.println((char) inChar);
This will only print the value of the first character that was input because System.in.read() only reads the first byte.
To read a whole line you could use a Scanner:
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Write something:");
// read input
String line = scanner.nextLine();
System.out.print("You entered ");
System.out.println(line);
}
}
Try this snippet.
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader brInput = new BufferedReader(isr);
String strInput = brInput.readLine();
System.out.println("You wrote "+strInput);
System.in.read reads only first byte from input stream
So if you enter
123
the first character is 1.So its corresponding ASCII is 49
If we enter
254
the first character is 2.So its corresponding ASCII is 50
Edit:This is explained also here
If trying to get user input into a string, using the code:
String X = input("\nDon't just press Enter: ");
and if they did't enter anything, to ask them until they do.
I've tried to check if it's null with while(x==null) but it doesn't work. Any ideas on what I am doing wrong/need to do differently?
input() is:
static String input (String prompt)
{
String iput = null;
System.out.print(prompt);
try
{
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
iput = is.readLine();
}
catch (IOException e)
{
System.out.println("IO Exception: " + e);
}
return iput;
//return iput.toLowerCase(); //Enable for lowercase
}
In order to ask a user for an input in Java, I would recommend using the Scanner (java.util.Scanner).
Scanner input = new Scanner(System.in);
You can then use
String userInput = input.nextLine();
to retrieve the user's input. Finally, for comparing strings you should use the string.equals() method:
public String getUserInput(){
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
if (!userInput.equals("")){
//call next method
} else {
getUserInput();
}
}
What this "getUserInput" method does is to take the user's input and check that it's not blank. If it isn't blank (the first pat of the "if"), then it will continue on to the next method. However, if it is blank (""), then it will simply call the "getUserInput()" method all over again.
There are many ways to do this, but this is probably just one of the simplest ones.
I would like to know about other ways of getting input from users using other classes like BufferedReader,etc rather than using Scanner class. So, was there any other way of getting input from the user? If so, was it efficient than Scanner class?
if you are using the Java SE6 or higher then you can make use of Console clas
Console console = System.console();
if (console==null){
System.out.print("console not available ");
}else {
String line = console.readLine("Enter name :");
System.out.print("your name :"+line);
}
You can do it simply by the following steps:
Use the BufferedReader Class and wrap it with the InputStreamReader Class.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
//string str = br.readLine(); //for string input
int i = Integer.parseInt(br.readLine()); // for Integer Input
Now since the readLine method throws an IOException you need to catch it. The whole code will look like this:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
//string str = br.readLine(); //for string input
int i = Integer.parseInt(br.readLine()); // for Integer Input
} catch(IOException ioe) {
ioe.PrintStackTrace();
}
You can use System.in directly, like this:
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
Although this may be a little faster than using the Scanner, it's not an apples-to-apples comparison: Scanner provides more methods for tokenizing the input, while BufferedReader can split your input into lines, without tokenizing it.
Use this:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
to create a reader for System.in, and you can use stdin.readLine() or something to get what you want.
Using a BufferedReader is MUCH more efficient than using a Scanner.
Here for example...
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
int num , num2;
String str[]=new String[2];
System.out.print("Please Enter Your First Number:");
str[0] = stdin.readLine();
System.out.print("Please Enter Your Second Number:");
str[1] = stdin.readLine();
num = Integer.parseInt(str[0]);
num2 = Integer.parseInt(str[1]);
A user can input data at the time of execution of the program without using a scanner class, and this can be done by using the following program.
class Demo
{
public static void main(String ar[])
{
int ab = Integer.parseInt(ar[0]);
int ba = Integer.parseInt(ar[1]);
int res = ab+ba;
System.out.print(res);
}
}
This is a basic program where a user can input data at the time of execution and get the desired result. You can add, subtract, Multiply, divide and concatenate strings, in CMD and a user can input data after compiling the java program i.e at the time of calling the class file. You just need to call the class file and then enter the data after a space.
C:\Users\Lenovo\Desktop>java Demo 5 2
Here ab= 5 and ba= 2. A user can have any number or string if he wants.