I am trying to run a java file in the command prompt. the project was made in NetBeans. so I tried running it with java -jar "D:\Java Projects\Algo1\dist\Algo1.jar" which is what NetBeans told me to run in the command prompt. however, I get the following:
my code is:
`
public static void main(String[] args) {
// TODO code application logic here
Scanner N = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Scanner K = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Scanner L = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println(K);
}
When you call System.out.println(K), java will print the argument (K) to the console. In this case the output tells you that you have an instance of the class java.util.Scanner and its properties.
When you want to read an input from the console, you should use the nextLine() method from the Scanner class, for example
String input = K.nextLine();
You can read more here: https://stackoverflow.com/a/11871792/7677308
Related
I am a beginner with java and programmin over all, So this the full code for a file reader program that counts words or displays text file content, I wanted to take user inputs for commands that I indicated using an if statement, but String printFileCommand = scan.nextLine(); is not working due to the error addressed below:
package com;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanTwo = new Scanner(System.in);
System.out.println("Please Enter Your File Path");
String filePath = scanTwo.nextLine();
scanTwo.close();
File fileInput = new File(filePath);
Scanner fileScanner = new Scanner(fileInput);
System.out.println(fileScanner.nextLine());
fileScanner.close();
System.out.println("Commands: PRINT.FILE --> Prints all file COUNT.WORDS --> Counts all words");
System.out.println("Type Command:");
Scanner scan = new Scanner(System.in);
String printFileCommand = scan.nextLine(); <----ERROR HERE
scan.close();
if (printFileCommand.contains("PRINT.FILE")) {
while (fileScanner.hasNextLine()) {
System.out.println(fileScanner.nextLine());
}
} else if (printFileCommand.contains("COUNT.WORDS")) {
int wordCount = 0;
while (fileScanner.hasNext()) {
String fileWords = fileScanner.next();
wordCount++;
// System.out.println(wordCount);
}
System.out.println(wordCount);
}
else {
System.out.println("COMMAND INVALID!");
}
}
}
```
**Terminal Output:**
PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING> c:; cd 'c:\Users\DR\Desktop\FIRST REAL PROGRAMMING'; & 'c:\Users\DR\.vscode\extensions\vscjava.vscode-java-debug-0.30.0\scripts\launcher.bat' 'C:\Program Files\AdoptOpenJDK\jdk-15.0.1.9-hotspot\bin\java.exe' '--enable-preview' '-XX:+ShowCodeDetailsInExceptionMessages' '-Dfile.encoding=UTF-8' '-cp' 'C:\Users\DR\AppData\Roaming\Code\User\workspaceStorage\458dc35931a3067a355426e5ceeeee32\redhat.java\jdt_ws\FIRST REAL PROGRAMMING_e263b9bc\bin' 'com.FileReader'
Please Enter Your File Path
E://texttwo.txt
This is my text file.
Commands: PRINT.FILE --> Prints all file COUNT.WORDS --> Counts all words
Type Command:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at com.FileReader.main(FileReader.java:21)
PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING>
So why is `String printFileCommand = scan.nextLine();` not working? I tried alot, but its not working...
It doesn't work because your stream for System.in is closed.
You can check it for example System.out.println(System.in.available()); and you will see:
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
at java.io.BufferedInputStream.available(BufferedInputStream.java:410)
you closed it in line: scanTwo.close();
I'm still trying to understand Java myself, but I think you don't exactly need to create and use multiple Scanners to collect data. Since you are searching for strings for the file creations, you could technically do something like:
Scanner scanner = new Scanner(System.in);
String filePath = scanner.nextLine();
With some of the other scanners you can keep since you're specifically calling the fileInputs within the Scanner, but when asking the user for data, I suggest using only one scanner source, but having something like the last line of code I shared as a template for updating your code! If I misunderstood something you're more than welcome to let me know. Thanks!
Please check this question:
NoSuchElementException - class Scanner
Your code will work if you remove the code:
scanTwo.close();
Or removing better:
Scanner scan = new Scanner(System.in);
And use scanTwo for reading (but you don't have to close the scanner with scanTwo.close()).
But I recommend you to read those answers to understand how it works.
I want to make a function that accepts input from the user via the Console as well as when piping input from a text file (the latter for testing purposes).
So far the work-around I found is to overload the function.
the version with the input from text file:
void game_run(String inputFileStream, PrintStream out) throws IOException {
int i=MAX_RETRY;
Scanner sc = new Scanner(new FileInputStream(inputFileStream),"UTF-8");
String guessed_code = new String();
System.out.println("insert input");
if (sc.hasNextLine()) {
guessed_code = sc.nextLine();
}
out.println(guessed_code);
}
And I call it in the main function as follows:
ms.game_run(args[1],System.out);
But when I want to run this from the command Line i have to pass the txt file as an argument to the programm like so :
java MasterMild ..\tests\inputs-1.txt > resss
And the second version just accepts normal Scanner:
void game_run() throws IOException {
Scanner sc = new Scanner(System.in); //The user inputs a value that gets stored
System.out.printf("insert input");
String guessed_code = new String(); //in the guessed_code variable
if (sc.hasNext()) {
guessed_code = sc.nextLine();
}
Now I want to modify my code so that it accepts input from both the console and also from piping the input as a text file to the Programm, like this:
cat ../tests/inputs-1.txt | java MasterMild > results
I need to make a simple Java program that writes it output to the cmd (the Command Prompt) window and reads user's input from there.
When I run the code from the IDE using the standard System.out.println it presents the output on the IDE (I use intelliJ) console view.
I guess this is a simple question and there are already answers for it here but I made several searches and did not find appropriate resolution.
That's it. your program now will output to cmd if you run it using cmd instead of IDE.
For input you can use scanner to read user input. or simply let user enter them all before running the program and include the args of main method in your logic to process user's input.
demo for u :)
public class testCMD {
public static void main(String[] args) {
testCMD obj = new testCMD();
System.out.println("Press command here:");
Scanner keyboard = new Scanner(System.in);
String command = keyboard.next();
//String command = "msconfig";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
I'm having some trouble reading in a file from the command line.
I've never used command line arguments before so I guess I'm a little lost.
Here's what I'm trying so far:
FileInputStream fin1 = null;
for (int i = 0; i < args.length; i++) //command line argument for file input
{
fin1 = new FileInputStream(args[i]);
}
//Scanner scan = new Scanner(fiin1);
I've commented out my scanner because I'm using a different method (into which I'm passing in fin1 as a parameter) and that method has a scanner in it. However, I'm not too sure if I still need the scanner there (maybe to pass into the other method as a param).
Anyway, if I run my code, I get a NullPointerException, which I assume comes from the fact that I initialized my FileInputStream as null. But if I'm changing it in the for loop, why does that matter?
Also, I need to keep my main method the way it is so I can do more in it.
Can anyone help?
Notice that it is called FileInputStream , and so we need to be using a File .
You can simply use a Scanner , and set it to System.in :
Scanner scanner = new Scanner(System.in);
And then afterwards, you can initialize that FileInputStream
How to Read Strings from Scanner in console Application JAVA?
Use following code.
if (args.length < 1) {
System.out.println("No file was given as an argument..!");
System.exit(1);
}
String fileName = args[0];
Scanner scanner = new Scanner(new File(fileName));
if you want to use a FileInputStream then change the last line to create a FileInputStream instance.
fin1 = new FileInputStream(fileName);
No need to use a for-loop if you are giving only one filename as the argument. You can run your code as follow.
javac MyClass.java //Compile your code(Assumed that your file is MyClass.java
java MyClass filename //Change filename with the path to your file
You are getting NullPointerException probably because you are not using filename as a argument when you run your java code.
First of all : when you run your code, you'll reach only the last argument.
You should do like this:
FileInputStream fileInputStream = null;
for (String argument : args) {
fileInputStream = new FileInputStream(argument);
//you should process your argument in block together with creating fis
Scanner scanner = new Scanner(fileInputStream);
//now, when a scanner copy is created, you can use it (or you can use your own
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("Input.txt"));
}
I have to give input file through command line
java -cp Projectfile.java < Input.txt
what change should I do in my program to fetch this file in BufferedReader?
You pass it as command line argument
java -cp Projectfile.java Input.txt
and access passed argument in args[]
BufferedReader br = new BufferedReader(new FileReader(args[0]));
Try this way. You may optionally include 'else' part. If you dont want else part then move the bufferreader statement in 'then' part. Run it as ->
java -cp . Projectfile Input.txt
Code ->
public static void main(String[] args) throws IOException, {
String file;
if ( args.length > 0 ) {
file = args[0];
}
//Optionally you can define the file name if not supplied in java command.
else {
file = "Input.txt"
}
BufferedReader br = new BufferedReader(new FileReader(file));
}
try the code below:
public static void main(String [] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(args[0]));
}
During the execution of your program, you pass the file as argument but then you never use it. By using args[0], you will be using the argument that you passed on:
java -cp Projectfile.java < Input.txt
First of all after initialising the BufferedReader class with "br" as its object, you need to write the following line
String str=br.readLine();
System.out.println(str);
Next you have to create a file Input.txt and place it in the same folder as that of your java file.
Next in the command prompt, write
javac Projectfile.java
Press Enter
java -cp . Projectfile < Input.txt
In this way it'll be done. Happy Coding Journey!!!