I have an assignment stating that "You can assume that input will come from standard input in a stream. You may assume that the markers have access to all standard libraries".
How do I go about reading several lines/inputs and saving all the inputs as one string and then outputting that string from a function?
Currently this is my function, but it's not working properly, at one stage it wasn't reading more than one line and now it doesn't work at all.
public static String readFromStandardIO() {
String returnValue = "";
String newLine = System.getProperty("line.separator");
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
System.out.println("Enter text...\n");
while (!(reader.readLine() == reader.readLine().trim())) {
userInput = reader.readLine();
returnValue += userInput;
}
System.out.println("You entered : " + returnValue);
return returnValue;
} catch (Exception e) {
}
return null;
}
Thank you for the assistance!
The problem is you're calling reader.readLine() three different times, so you'll end up comparing two completely different strings and then recording yet another one.
Also, it's generally frowned upon to compare strings using == (as comparing Objects with == asks if they are the same actual object (yes, Java's forgiving in that regard with strings, but it's still frowned upon)).
You'll need to do something more akin to:
public static String readFromStandardIO() {
String returnValue = "";
System.out.println("Reading Strings from console");
// You use System.in to get the Strings entered in console by user
try {
// You need to create BufferedReader which has System.in to get user
// input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println("Enter text...\n");
while (true) {
userInput = reader.readLine();
System.out.println("Finally got in here");
System.out.println(userInput);
returnValue += userInput;
if (!userInput.equals(userInput.trim())) {
break;
}
}
System.out.println("You entered : " + returnValue);
} catch (Exception e) {
}
return returnValue;
}
Related
I'm trying to write a method that:
Prints out a message (Something like: "Paste your input: ")
Waits that the user presses enter.
Reads all the lines, that got pasted and adds them up in one String.
(An empty line can be used to determine the end of the input.)
The first syso does the printing part and also the first line gets read correctly, but then it never exits the while loop. Why? There has to be an end?
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = buffer.readLine()) != null && !line.isBlank())
res += "\n" + line;
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Ive already seen the following sites, but they all didn't help:
How to read input with multiple lines in Java
https://www.techiedelight.com/read-multi-line-input-console-java/
Make the console wait for a user input to close
Edit:
The same bug applies for:
public static String readInput(String msg) {
System.out.print(msg);
String res = "";
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
System.out.println(res);
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Edit 2:
I've tried this code in my actual project and in a new test-project, but with different results. Here is a video of that test.
Why wouldn't use this statement?
while (!(line = buffer.readLine()).isEmpty())
In this case sending empty line will exit the loop.
Although, if you insert large text with empty lines (for example, the beginning of a new paragraph, or a space between them) will terminate the program.
I want to have a method that returns the value that is presentend in the while loop. My code represents the reading of a txt file, where I read line by line and my goal is to return everytime it founds a line but is is showing me the same number over and over.
public String getInputsTxtFromConsole() {
String line = "";
//read inputs file
try {
Scanner scanner = new Scanner(inputFile);
//read the file line by line
int lineNum = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
}
} catch (FileNotFoundException e) {
}
return "";
}
As Nick A has said the use of return has, in this context two uses: return the value of a function and exit the function. I you need all the values as the are generated you can, for example,
Call a method that consume the new value:
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
ConsumerMethod(line);
}
Store in a global var like ArrayList, String[],...
Print it System.out.println(line).
...
But you cannot return a value and expect that the function continues working.
As I mentioned, pass the same scanner as a parameter to a method that reads a line and returns the line. You may want to define how it responds once there are no remaining lines.
public String getInputsTxtFromConsole(Scanner scanner) {
try {
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
} catch (FileNotFoundException e) {
}
return null;
}
I would also recommend using a different class to read from a file. BufferedReader would be a better approach.
BufferedReader in = new BufferedReader(new FileReader (file));
... // in your method
return in.readLine(); //return null if the end of the stream has been reached
I'm writing a simple program where the program asks the user to input some strings and a certain output in generated based on the user's input. But when I run the code the I got some error.Errors I've also tried the scanner import but the same exceptions pop up. And when I moved the imports outside of my main I got 3 different errors again.Errors At this moment I don't need the method to be looped or anything, just want to have it so the program can spit out some output based on user's input. Thanks.
public class Question {
public static void main(String arg[]) {
import java.io.BufferReader;
BufferReader br = new BufferReader(new InputStreamReader(System.in));
String input = br.readLine("who's your daddy?");
if (input = "you're my daddy.") {
System.out.println("correct");
else {
System.out.println("try again");
}
}
}
}
Edit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Question {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = in.readLine();
if ("you're my daddy.".equals(input)) {
System.out.println("correct");
} else {
System.out.println("try again");
}
} catch (IOException ex) {
System.out.println("Error reading from System.in");
}
}
}
Another hint for String comparisons:
It is better to put the String constant in the first place of the comparison to avoid NullPointerExceptions.
if ("you're my daddy.".equals(input)) {
// ...
}
And a brief explanation of why == is not correct here:
This checks if two objects are the same (identity). Every time you write "you're my daddy." a new String is created. Therefore the comparison with == would never be true although the content of the String is identical.
Comparisons are achieved with ==, not =. And, in Java, for Strings, you should use the equals() method fot that
input.equals("you're my daddy.")
To compare things, you use ==, not =. That is assignment.
However, input is a string. So you want to use -
if (input.equals("you're my daddy.")) {
Read up about this here - What is the difference between == vs equals() in Java?
In your code..
you can use buffered reader outside of main like this
private static BufferReader br = new BufferReader(new InputStreamReader(System.in));
if (input = "you're my daddy.") { // by using equals method. your code is wrong here
System.out.println("correct");
// not closing curly braces here
public class V
{
public static void main ( String [] args )
{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your input string: ");
String input = reader.readLine();
System.out.println("Your input is: " + input);
String input1="you're my daddy.";
if (input.equals(input1))
{
System.out.println("correct");
}
else
{
System.out.println("try again");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
} enter code 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'm developing an application that has to receive multiple pieces of input from the user's terminal, while elegantly handling invalid input and prompting the user to re-enter it. My firs thought would be to have a while loop whose body will take the input and verify it's validity, setting a flag when it gets valid input. This flag will mark the stage the application is at and will determine what type of input is required next, and will also be used as the terminating condition of the loop.
While functional, this seems rather inelegant and I was wondering if there was a way I could simply write a function that is called whenever the return key is pressed to indicated that there is new input to be parsed. Something along the lines of
public class Interface {
public void receiveInput( final String input ){
// Parse 'input' for validity and forward it to the correct part of the program
}
}
Perhaps this could be achieved by extending some Java class and reimplementing one of it's functions that would normally handle such an event, but that's perhaps my C++ background talking.
I'm not allowed to use any external libraries, other than those requires for building and unit testing.
While reading from the console you can use BufferedReader
BufferedReader br = new BufferedReader( new InputStreamReader( System.in));
and by calling the readLine function, it will handle new line :
String readLine = br.readLine();
You can sure have a class in which there would be a function which reads the information and continue.
Here is the sample code for your reference
public class TestInput {
public String myReader(){
boolean isExit = true;
while (isExit){
System.out.print("$");
BufferedReader br = new BufferedReader( new InputStreamReader( System.in));
try {
String readLine = br.readLine();
if (readLine != null && readLine.trim().length() > 0){
if (readLine.equalsIgnoreCase("showlist")){
System.out.println("List 1");
System.out.println("List 2");
System.out.println("List 3");
} if (readLine.equalsIgnoreCase("shownewlist")){
System.out.println("New List 1");
System.out.println("New List 2");
} if (readLine.equalsIgnoreCase("exit")){
isExit = false;
}
} else {
System.out.println("Please enter proper instrictions");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Finished";
}
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("Please Enter inputs for the questions asked");
TestInput ti = new TestInput();
String reader = ti.myReader();
System.out.println(reader);
}
Here is the output:
Please Enter inputs for the questions asked
$showlist
List 1
List 2
List 3
$shownewlist
New List 1
New List 2
$exit
Finished
Hope this helps.