how to get input through System.in? - java

I am a beginner Java programmer, and I use this Java Tutorial.
In the I/O from the Command Line page, it uses InputStreamReader cin = new InputStreamReader(System.in); to get user input from the command line. But when I try to use it, nothing happens. I have a very simple program, and it's just to test whether this works, but it doesn't.
import java.io.*;
public class TestInput {
public static void main(String args[]) {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
if(cin.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}
}
It just says, "hello, guest" and exits, without letting me input anything.
I'm assuming this is supposed to work similar to System.console, but if this isn't what it's supposed to be like, please tell me.
What is wrong with my code?
thanks for any answers.
EDIT
From the edits I'm getting, I suppose I have to use cin.readline() to actually read the input.
I got my program to work. thanks!

try{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String name= cin.readLine();
if(name!=null && name.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}catch(IOException e){
}

You have to read the input:
if(cin.readLine().equals("jon")) { // or "jon".equals(...) to handle null
(See BufferedReader.readLine())
You will also have to handle the potential IOException with a try-catch.
With cin.equals("jon"), you are testing if the BufferedReader object cin is itself equal to the string "jon", which is clearly false.

You need to use, cin.readLine()
Oracle Docs.

if(cin.readLine().equals("jon"))
Also, you need to handle the IOException

Related

Regarding Connecting Two Java Programs

So I'm trying to practice connecting out of one java program to the input of another program and I'm wondering if the way I did it is efficient or if there's a better way. I'm saving a string into a text file in the first program and reading the string then printing it out in the second. Is there a way to just cut out using the text file as a middle man?
Here's my first program:
import java.util.Scanner;
import java.io.*;
public class pip1{
public static void main(String[] args){
String inString = "";
Scanner sc = new Scanner(System.in);
inString = sc.next();
try{
PrintWriter out = new PrintWriter("word.txt");
out.println(inString);
out.close();
} catch(FileNotFoundException ex){ }
}
}
and here is the second:
import java.io.*;
public class pip2{
public static void main(String[] args) {
String fileName = "word.txt";
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String outString = br.readLine();
br.close();
fr.close();
System.out.println(outString);
} catch (FileNotFoundException ex) {}
catch (IOException ex) {}
}
}
Thanks!
I suppose what you want is a pipe, which acts as a "intermediate wire" between two processes without using an "temporary file".
So I recommend you to read doc about Pipes in JAVA.
Here's a link of tutorial.
Also see javadoc about PipedInputStream
javadoc about PipedOutputStream
What's more, if your OS supports IO redirection from terminal, then just do it without using , as Andy says. This would be the easiest.
Just write to System.out in the first one, read from System.in in your second, and use a pipe to connect the output of the first into the second when you run the two commands:
java pip1 | java pip2

How to write in a file from keyboard input in java?

I wrote a program to write in a file...
package iofile;
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
String s;
File file=new File("C:\\Users\\Rajesh\\oacert\\Learn\\src\\iofile\\raj.txt");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
try{
PrintWriter pr=new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
System.out.println("enter to write in a file...");
s=br.readLine();
while(s!=null){
pr.println(s);
s=br.readLine();
}
pr.close();
}
catch(Exception e){
}
}
}
But it's unable to write anything in raj.txt. What's causing this? Thanks in Advance
NOTE: raj.txt exists in the mentioned directory...
I don't think s can ever be null in your code. You should better use a terminating string to exit the program. Try replacing this:
while(s!=null){
with
while(!s.equals("exit")){
and enter 'exit' to terminate the loop
Use write method.
Put an end condition, such as s.equalsIgnoreCase("Exit")
Call method flush;
Try the following code.
while(!s.equalsIgnoreCase("Exit")){
pr.write(s);
pr.write("\n");
s=br.readLine();
}
pr.flush();
pr.close();

JAVA: How to check if website document contains a word?

I currently have the follow method:
try {
URL url = new URL("http://auth.h.gp/HAKUNA%20MATATA.txt");
Scanner s = new Scanner(url.openStream());
}
catch(IOException ex) {
BotScript.log("Something went wrong =/ Error code:");
ex.printStackTrace();
stop();
}
However, how do I check if it contains a word? I've never worked with Scanners before and I found this snippet online.
Thank you.
Okay, that looks good so far.
You can then use Scanner's next() method to get each word. You can also query hasNext() to see if there's another token available to avoid errors.
boolean foundPumbaa = false;
while (s.hasNext()) {
if (s.next().equalsIgnoreCase("pumbaa")) {
foundPumbaa = true;
System.out.println("We found Pumbaa"); // do something
break;
}
}
if (!foundPumbaa) {
System.out.println("We didn't find Pumbaa");
}
EDIT in response to comment:
Yes, you can turn the text into a String. The best way to do this is probably with a BufferedReader.
From the Java Tutorial, "Reading Directly from a URL":
The following small Java program uses openStream() to get an input
stream on the URL http://www.oracle.com/. It then opens a
BufferedReader on the input stream and reads from the BufferedReader
thereby reading from the URL. Everything read is copied to the
standard output stream:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
In a real program, instead of main throws Exception, you'd have that in a try-catch block and catch an IOException and some various URLExceptions. But this should get you started.

Java Read from file to Array runtime error

import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();

How to call another java program using eclipse

The following code(when executed) prompts the user to enter any java class name to execute.
import java.io.*;
public class exec {
public static void main(String argv[]) {
try {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the java class name");
String s=br.readLine();
Process pro=Runtime.getRuntime().exec(s);
BufferedReader in=new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line=null;
while((line=in.readLine())!=null) {
System.out.println(line);
}
in.close();
} catch(Exception err) {
err.printStackTrace();
}
}
This code works fine if I'm using command prompt and I'm able to execute another java program. But I'm unable to do the same using eclipse.No output or error is showing up once I enter the java class name.
I'm new to eclipse. Need help.
You can't "execute" a java class, so your code as posted can't work.
Instead, you'll need to execute "java" and pass to it the classpath and class name as parameters, something like this:
String s = br.readLine();
String[] cmd = {"java", "-cp", "/some/path/to/your/jar/file", s};
Process pro = Runtime.getRuntime().exec(cmd);
Do you just enter the name of the class, or do you also enter the directory of where the program is located? I think it doesn't work in eclipse because you need to specify where the file is... like C:\Users\Me\workspace\ProjectName\src\filename

Categories

Resources