I'm currently attempting to write a role-playing game with Eclipse (don't know how far I'll get, but who knows) and I'd like to prompt the user to answer with a sentence/phrase.
I'm learning very basic Java right now, but we know how to prompt the user to enter in either an integer or a double variable/number (er... mind is a little messed up) - similar to:
variable=input.nextInt();, or input.nextDouble();
Can anyone please list how to prompt the user for a phrase, and how to make the program recognize that certain phrase (and get results)? Thank you.
(One final note: I'm not the best programmer, so can you please list the simplest ways to do so?)
Probably your input is a Scanner, so just use nextLine() to get a line of text. That will wait for the user to enter an arbitrary amount of text and press enter, then you'll get all the text they entered.
Soln:
public static void main(String[] args) {
System.out.println("Enter the phrase");
String line;
try {
BufferedReader input =new BufferedReader(new InputStreamReader(System.in));
while ((line = input.readLine()) != null) {
System.out.println(line);
if(!line.isEmpty()) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
System.out.println("token=" + st.nextToken());
}
}
}
input.close();
} catch (IOException e){
e.printStackTrace();
}
System.out.println("DONE");
}
Related
In Java i take Input using standard Scanner and BufferedReader Classes like:
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
or
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(br.readLine());
but taking input like this takes a lot of running time. I would like to know the faster way to take input. Thanks in advance
Edit: I have seen top java coders like uwi who take input in a very different way. They kinda create their own reader class. I dont get it that how their program becomes fast in runtime.
In the article below, the author discusses three different ways for reading input from the user in the console. Each way is fairly easy to use and also has its own advantages and drawbacks.
The below mechanisms are discussed and examples are provided.
There is also a pros and cons section as well.
Link:
http://www.codejava.net/java-se/file-io/3-ways-for-reading-input-from-the-user-in-the-console
Link:
Most Efficient Way of Taking User Input in Java
Options:
Scanner Class->
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt();
DataInputStream->
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
BufferedReader ->
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Your name is: " + name);
Console->
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Quote from dejavu:
"BufferedReader is a lot faster than Scanner because it buffers the character so you don't have to access the file each time you want to read a char from it.
Scanner are of particular use such as reading primitive data type directly and is also used for regular expressions.
I have used Scanner and BufferedReader both and BufferedReader gives significant fast performance. You can test it yourself too."
from:which to choose buffered reader or scanner from performance point of view
If you want a fast way to input via stdin (and, if I understand you correctly, you want a fast way to repeatedly feed inputs to your programs), your best bet is to pipe or redirect canned responses e.g.
$ java MyReadingClass < mycannedinput.txt
so you can build your class to take interactive input via stdin, and then use a simple shell redirection to feed in canned input such that you don't have to retype it each time.
The Fastest way to take userinput in java in particularly Competitive coding is to make own FastReader class by using bufferedReader and StringTokenizer.
This method uses the time advantage of BufferedReader and StringTokenizer and the advantage of user defined methods for less typing and therefore a faster input altogether. This gets accepted with a time of 1.23 s and this method is very much recommended as it is easy to remember and is fast enough to meet the needs of most of the question in competitive coding.
Implementation :
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
In Main File :
public static void main(String[] args)
{
FastReader s=new FastReader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0)
{
int x = s.nextInt();
if (x%k == 0)
count++;
}
System.out.println(count);
}
Source Link : https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
This is repeated question and an optimized way to read and write data in java can be found at the below link.
https://stackoverflow.com/a/49957378/5076337
These classes are very useful in reading inputs and writing outputs in programming contests.
I am trying to make the user input an Airport Name, and the program will search from a text file to get the matching Code, right now I only need it to read the line. I have looked into many similar questions in here, but nothing works for me. The program return the else result rather than the found result.
This is my code so far
public static void main (String[] args) throws IOException
{
File file = new File("codes01.dat");
Scanner myFile = new Scanner(file);
Scanner kb = new Scanner(System.in);
String line;
System.out.println("Hey man, this is totally leigt, just enter an Airport code and I'll hook you up.");
System.out.print("First, y'all need to give me the file name: ");
String fileName = kb.nextLine();
if (fileName.equalsIgnoreCase("codes01"))
{
System.out.print("Cool, now give me your Airport Name: ");
String AirportName = kb.nextLine();
while (myFile.hasNextLine())
{
line = myFile.nextLine();
String name = myFile.next();
System.out.println(line);
if(name.equalsIgnoreCase(AirportName))
{
System.out.println("IT'S WORKING, I DON'T KNOW HOW BUT IT IS "+line);
break;
}
else
{
System.out.println("Sorry, dude, ain't no airport in my VERY limited list with that name");
break;
}
}
}
The program return the else result rather than the found result.
That is because you are breaking out of the loop after testing the first line in your file.
Look carefully at your code ... in context.
if(name.equalsIgnoreCase(AirportName)) {
System.out.println("It is working");
break;
} else {
System.out.println("Sorry");
break; // What????
}
Why are you using the break statement in the if-else block? Try to get rid of the break statement and then execute your code.
if(name.equalsIgnoreCase(AirportName))
{
System.out.println("The name of Airport matches");
}
else
{
System.out.println("Sorry No Match Found");
}
Look closely at these two lines. There's a problem there. Step through the code in your head pretending you are the Scanner class.
line = myFile.nextLine();
String name = myFile.next();
I have a set of instructions in a text file:
LoadA 0
LoadB 1
Add
Store 0
LoadA 2
etc...
I know I can use Scanner and hasNextLine but not sure how to implement this and have the instructions read and understood.
As much as the people above would like you to do this on your own I will answer this question because I remember how difficult it was to learn. As long as you learn from the and don't just copy them this should be useful.
Scanner sc = new Scanner(System.in); //read from the System.in
while (sc.hasNextLine()) { //this will continue to itterate until it runs out
String[] x = sc.nextLine().split(" ");
//this takes your input and puts it into a string array where there is a
//space e.g. ["LoadA", "0"]
}
I hope this helps. You are still required to solve the problem. You now have the ability to get the content now. Good luck.
Scanner inFile = null;
try
{
// Create a scanner to read the file, file name is parameter
inFile = new Scanner (new File("whatever.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!");
// Stop program if no file found
System.exit (0);
}
then,
while(inFile.hasNextLine()){
(some variable) = inFile.nextLine();
(do something to that variable);
}
if this doesn't solve the question, I would recommend taking a look at http://www.cs.swarthmore.edu/~newhall/unixhelp/Java_files.html
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have learnt about BufferedReader as well as BufferedWriter, so I decided to create a small text processor for the command line (meaning without interface, just in cmd/terminal). It asks a user for document name (Which will then create a file) and then user can type sentences. Each time user presses "enter" button, text is entered into the file and new line is created and then allowing user to type more. At the end, it will display a message saying file is created.
NOW, I have encountered a problem where user would not be able to stop the process of entering data and creating file, because the program kept creating new lines despite entering nothing or quit keyword(which i stated in the code in order to quit the program.)
Here is my original code:
import java.io.*;
class TextProcessor
{
public static void main(String[] args)
{
try
{
System.out.println("Please enter name of the file");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //User input
String file = in.readLine();
BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //Creating file as well as instance for inputting text to the file.
System.out.println("Enter text");
String line = "";
do
{
line = ins.readLine();
System.out.println(line);
writer.write(line);
System.out.println("Second " + line);
writer.newLine();
}
while(line != "quit()");
//while(line != null);
in.close();
writer.close();
System.out.println("Text is created with entered text");
}
catch(IOException e)
{
System.out.println("Error occured");
}
}
}
However, I found a solution to this, which is replacing do-while block with while one:
int counter = 0;
while(counter != 1)
{
line = in.readLine();
writer.write(line);
if(line.equals("quit()"))
{
++counter;
}
else {writer.newLine();}
}
I have a question about this now, why can't I use do-while statement instead of while, even if it seems logical that the program would work? Thank you for reading this!!!!
P.S. I also wonder if I can bring small improvements to this or any other way creating this type of program. Thanks if you give feedback!
Probably the error asked about the most.
Answer can be found here: How do I compare strings in Java?
while(line != "quit()");
must be
while(!line.equals("quit()"));
I am creating a java application and I need to get the user PINs from the text file. I used the following code below, but is it not working properly. Could anyone please help me out soon.....
String typedPIN="";
Menus obj1=new Menus();
BufferedReader getIt=new BufferedReader(new InputStreamReader(System.in));
String userPIN="";
try{
BufferedReader br = new BufferedReader(new FileReader(new File("D:\\Studies\\BCAS\\HND\\Semester 1\\Programming Concepts\\Assignment\\AccountPIN.tab")));
String strLine=null ;
System.out.println("Enter PIN");
userPIN=getIt.readLine();
while ((strLine = br.readLine()) != null) {
if(userPIN.equals(strLine)){
System.out.println("You have login!");
obj1.MainMenu();
}
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
Assuming this is your input data
PIN AccountNo Balance
1598 01-10-102203-0 95000
4895 01-10-102248-0 45000
9512 01-10-102215-0 125000
6125 01-10-102248 85000
You will need to split each line into its consituent parts, you could use the Scanner class to do this, as it will let you extract the pin / account number as Strings and the balance as a Double/Integer.
At the moment you are comparing the user input against the whole line, so you would need to enter a pin 1598 01-10-102203-0 95000 rather than 1598 in order to login.
I suggest you split this into to two methods, one which when given a file returns a Collection of Account objects, and another which handles the login.
You could re-write your while loop to enable you to give a useful error message if you don't get a valid pin, e.g.
final File data = new File("D:\\Studies\\BCAS\\HND\\Semester 1\\Programming Concepts\\Assignment\\AccountPIN.tab");
Account userAcc = null;
for (Account acc : getAccounts(data)) {
if(userPIN.equals(acc.getPin())){
userAcc = acc;
}
}
if (userAcc == null) {
obj1.MainMenu();
} else {
// display error
}