For the following program i am expecting output as
Enter any Value : 3
You Entered 3
But i am not getting output, instead in output java is expecting some input without displaying "Enter any Value". If i enter any value then it will display the output as
3
Enter any value : You Entered 3.
Here is my code:
import java.io.*;
// System.in is an object of InputStream - byte stream
class ConsoleInputDemo{
public static void main(String args[]) throws IOException{
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in)); // This will convert byte stream to character stream
PrintWriter consoleOutput = new PrintWriter(System.out);
consoleOutput.println("Enter any Value : ");
int c= consoleInput.read();
consoleOutput.write("You entered " + c);
consoleInput.close();
consoleOutput.close();
}
}
consoleOutput.println didn't print anything until it close(). Use
System.out.println("Enter any Value : ")
instead of
consoleOutput.println("Enter any Value : ");
Or close consoleOuput if you want to view the text.
consoleOutput.print("Enter any Value : ");
consoleOutput.close();
System.out.print("Enter any Value : ");
try {
int c=Integer.parseInt(new BufferedReader((new InputStreamReader(System.in))).readLine());
System.out.println("Entered Character: " +c);
} catch (IOException e) {
e.printStackTrace();
}
This simple code might help you achieve your requirement.read() will just give you ascii value so I preffer using readline() method to get actual values. Offcourse it will return string so just parse it to get integer.
Related
I used the information from this link to write the following code below to run a Python script and have it return a single string returned:
public static void Option_2_Output()
{
Scanner Option2_Input = new Scanner(System.in);
System.out.println("");
System.out.println("===============================================");
System.out.println(" Testing Means of Two Groups ");
System.out.println("===============================================");
System.out.println("");
String Option2_program = "python";
String Option2_path = "C:\\PathtoScript\\Python_Test.py";
try{
String Option2_datapath;
System.out.print("Please type the location of your Data : ");
Option2_datapath = Option2_Input.next();
ProcessBuilder Option2_process = new ProcessBuilder(Option2_program,Option2_path,"" + Option2_datapath);
Process Option2_Output = Option2_process.start();
BufferedReader in = new BufferedReader(new InputStreamReader(Option2_Output.getInputStream()));
String Option2_Final = new String(in.readLine());
System.out.println(Option2_Final);
}catch(Exception e){
System.out.println(e);
}
}
The object Option2_Final streams the last printed output from the Python script back as a string. How do I get more than one value back?
Only one line is being streamed back because there's only one readLine() function being utilized. A for-loop could be written to search for each additional line or objects could be created for each line you're intending to pass back:
BufferedReader in = new BufferedReader(new InputStreamReader(Option2_Output.getInputStream()));
String Option2_Final_1 = new String(in.readLine()); //Line 1
String Option2_Final_2 = new String(in.readLine()); //Line 2
System.out.println(Option2_Final_1); //Print Line 1
System.out.println(Option2_Final); //Print Line 2
I am trying to read information from a file to interpret it. I want to read every line input. I just recently learned about bufferedreader. However, the problem with my code is that it skips every other line.
For example, when I put in 8 lines of data, it only prints 4 of them. The even ones.
Here is the code:
import java.io.*;
import java.util.Scanner;
public class ExamAnalysis
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
int numOfQ = 10;
System.out.println();
System.out.println("Welcome to Exam Analysis. Let’s begin ...");
System.out.println();
System.out.println();
System.out.println("Please type the correct answers to the exam questions,");
System.out.print("one right after the other: ");
Scanner scan = new Scanner(System.in);
String answers = scan.nextLine();
System.out.println("What is the name of the file containing each student's");
System.out.print("responses to the " + numOfQ + " questions? ");
String f = scan.nextLine();
System.out.println();
BufferedReader in = new BufferedReader(new FileReader(new File(f)));
int numOfStudent= 0;
while ( in.readLine() != null )
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " + in.readLine());
}
System.out.println("We have reached “end of file!”");
System.out.println();
System.out.println("Thank you for the data on " + numOfStudent+ " students. Here is the analysis:");
}
}
}
I know this may be a bit of a bad writing style. I am just really new to coding. So if there is any way you can help me fix the style of the code and methods, I would be really thrilled.
The point of the program is to compare answers with the correct answer.
Thus I also have another question:
How can I compare strings with the Buffered Reader?
Like how can I compare ABCCED with ABBBDE to see that the first two match but the rest don't.
Thank you
the problem with my code is that it skips every other line
Your EOF check thows a line away on each iteration
while ( in.readLine() != null ) // read (first) line and ignore it
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
in.readLine()); // read (second) next line and print it
}
to read all line do the following:
String line = null;
while ( null != (line = in.readLine())) // read line and save it, also check for EOF
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
line); // print it
}
To compare Strings you need to use the String#compareTo(String other) method. Two Strings are equal if the return value is 0.
You don't compare Strings with readLine(). You compare them with String.equals().
Your reading code skips every odd line for the reason mentioned in the duplicate.
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.
Ok so i have inputted a number of records to a text file and i can both write to and read from this file, but i am now attempting to search through this textfile and have encountered a problem.
package assignmentnew;
// Import io so we can use file objects
import java.io.*;
import java.util.Scanner;
public class SearchProp {
public void Search() throws FileNotFoundException {
try {
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your housenumber: ");
input = user.next();
Scanner housenumber = new Scanner(new File("writeto.txt"));
while (housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
if (input.equals(id))
{
System.out.println("House number is: " + id + "and" + line);
break;
}
if(!housenumber.hasNext()) {
System.out.println("no house with this number");
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
No matter what value i enter i am told that the house number is not present in the file, but obviously it is, any ideas?
Addendum:
File Structure in textfile.
27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached
10,Downing Street,London,sw19,9,1000000,Terraced
The default delimiter for a scanner is white-space, and not ,.
You have to use housenumber.useDelimiter(","); and the code will work.
EDIT:
Set it before the while.
And that is what I get for example for 27.
Please enter your housenumber:
27
House number is: 27 and ,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced