Can't use the Scanner class - java

I just started studying JAVA. I'm trying something very simple: Request a argument from the user on the prompt. I made this code:
import java.util.Scanner;
public class Request
{
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("What's your name?");
String name = s.nextLine();
System.out.println("Welcome " + name);
}
}
then I compile it, and when I execute it with
Java -cp Request
Instead of a prompt expecting a parameter
It prints all the options of the JAVA command as if I had coded this:
java -help
Why is that happening?

Use java Request, or maybe java -cp . Request ; the -cp option provides the JVM with a classpath, which should be a list of jars or directories containing .class files.
As Klitos mentions, you can set the CLASSPATH environment variable to provide a default classpath. Setting it to include the current directory . is common practice and spare you from having to use -cp . when invoking Java.
In Windows, the variable is %CLASSPATH% and is a ;-separated list of windows pathes.
In Linux (and MacOS AFAIK), the variable is $CLASSPATH and is a :-separated list of unix pathes.

Related

Trying to understand how to create a jar file that opens terminal and takes in a argument

I finished creating a program but I was told that my program
must be a Java application that takes as a command line argument the name of the file."
I understand I can use the jar command in terminal but I don't undestand how you open the terminal and take a file name as a argument. I was wondering if someone could explain what code is required to do this.
Thanks alot.
I tried creating a basic jar file in terminal with the line "jar cvf findOptimalTransport.jar ." but the jar file does not open, I think its because the current implementation takes the users input with a scannar in the code and prints via the terminal. However, this wont work because a terminal window is not opened with this command.
It doesn't have to be a jar file. Command line arguments can be entered from the command line, when you run your application.
Let me give you an example, about how this works. Let's say you have the below simple Java application:
public class MyApplication{
public static void main(String[] arguments){
System.out.println("Hello World!");
}
}
That public static void main() is a method; and more specifically the main method of your application which is what is executed when compiled and ran.
To compile and then run it, you type in the command line/terminal:
javac MyApplication.java //this will compile it
java MyApplication //this will run the main method of MyApplication
But what is that parameter in the main method? What is String[] arguments ?
When you run your program, whatever you type after the application name is an argument, of type String and it is stored in the String array String[] arguments (or most commonly String[] args).
What this means, is that, if you execute your application like this:
java MyApplication some_file.txt // Run application with one arg.
You can access that argument like so:
public class MyApplication{
public static void main(String[] arguments){
System.out.println("Hello World!");
System.out.println("You entered: " + arguments[0]);
}
}
Output:
Hello World!
You entered: some_file.txt
Note: To run a jar file, you need to navigate to the folder that the jar file is in and from the command line you can run it by typing:
java -jar <jarname>.jar

How to compile Java class with external library in Windows command line?

I have an assignment: Write a client program Permutation.java that takes an integer k as a command-line argument; reads in a sequence of strings from standard input using StdIn.readString()...
Here is my code:
public class Permutation {
public static void main(String[] args) {
int k = Integer.parseInt(args[0]);
String[] inputStrings = StdIn.readStrings();
}
}
How to compile it in Windows command line?
I tried
javac Permutation.java
But got an error
error: cannot find symbol
String[] inputStrings = StdIn.readStrings();`
I use IntelliJ IDEA, external library StdIn is added to the project.
To compile it with the library you have to add it to the classpath. This is accomplished with the -cp argument followed by the library which contains your referenced class.
javac -cp StdIn.jar Permutation.java
To run it with command line, similarly use
java -cp StdIn.jar Permutation
See also https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html

How to parse file patterns using Apache commons CLI

I'm trying to parse my command line arguments using the apache commons CLI. It might be a bit heavy handed for the example here, but it makes sense in the context of the program I'm creating. I'm trying to read a file pattern filter, similar to what grep uses to select files to process.
My Argument looks like this:
Program --input *.*
I've written a test program to see what the parser is seeing;
public static void main(String[] args) {
Options options = new Options();
options.addOption(new Option(INPUT_FILTER_SHORT, INPUT_FILTER_LONG, true, INPUT_FILTER_DESCRIPTION));
CommandLineParser parser = new BasicParser();
CommandLine cmd = parser.parse(options, args);
System.out.println(cmd.getOptionValue(INPUT_FILTER_SHORT));
}
This prints out:
.classpath
If I change my arguments to:
Program --input test.txt
I get the output:
test.txt
I'm assuming that I have to do something to tell apache commons what * is not a special character? I can't seem to find anything about this online.
I'm experiencing this on Windows (7). I'm fairly certain it's the *.* which is causing the issue as when I swap to using patterns that don't use *, the expected pattern shows up.
Your problem isn't really to do with Commons CLI, but to do with how the shell and the Java executable together process the parameters.
To eliminate other factors, and see what's going on, use a short Java program:
public class ArgsDemo {
public static void main(String[] args) {
for(int i=0; i<args.length; i++) {
System.out.println("" + i + ": " + args[i]);
}
}
}
Play with java ArgsDemo hello world, java ArgsDemo * etc. and observe what happens.
On UNIX and Linux:
Java does no special processing of *. However, the shell does. So if you did:
$ mkdir x
$ cd x
$ touch a b
$ java -jar myjar.jar MyClass *
... then MyClass.main() would be invoked with the parameter array ["a","b"] -- because the UNIX shell expands * to files in the current directory.
You can suppress this by escaping:
$ java -jar myjar MyClass * // main() sees ["*"])
(Note that a UNIX shell wouldn't expand *.* to .classpath because this form would ignore "hidden" files starting with .)
On Windows
cmd.exe does not do UNIX-style wildcard expansion. If you supply * as a parameter to a command in Windows, the command gets a literal *. So for example, PKUNZIP *.zip passes *.zip to PKUNZIP.EXE, and it's up to that program to expand the wildcard if it wants to.
Since some release of Java 7, the Java executable for Windows does some wildcard to filename expansion of its own, before passing the parameters to your main() class.
I've not been able to find clear documentation of Java-for-Windows' wildcard expansion rules, but you should be able to control it with quoting, escaping the quotes to prevent cmd.exe interpreting them:
> java.exe -jar myjar.jar MyClass """*.*"""
(Untested as I don't have a Windows box handy, and quoting in cmd.exe is a bit of a beast - do please experiment and either edit the above or leave a comment)

Packaging a jar with preconfigured command line arguments

I am wondering if there's a way to create a jar that includes some command line arguments in it, the arguments that are usually passed in the command line when one tries to start up the jar (these parameters are then passed on to the main function). Basically instead of starting my app with
java -jar myapp.jar "arg1" "arg2", I want to start my app with
java -jar myapp.jar
and have "arg1" and "arg2" passed to the main function.
The reason behind this is that I want to deploy this to different environments, and I want my jar to contain different parameters according to the environment it's being deployed at.
Maybe there's another way to achieve similar results ??
Cheers.
PS: Looking for a maven solution.
Edit: I'll add a complete example to make this a bit more clear:
Let's say I have 2 environments: "Production" and "Test". I want to run the jar in the same way no matter in what environment I deploy it. So I always want to run it with:
java -jar myapp.jar
But! In order for my 2 environments to run ok, I need the Production environment jar to start it's main method with an argument "prod" and I need the Test environment jar to start it's main method with an argument "test".
If I correctly understood your problem, in your main() you could define a simple logic to handle the case where you do not specify any input parameter; the logic could retrieve the desired values according to the correct platform/env.
As an example:
public class Test01
{
public static void main(String... aaa)
{
// Check input
if(aaa.length == 0) {
/* Insert logic to retrieve the value you want, depending on the platform/environment.
* A trivial example could be: */
aaa = new String[2];
aaa[0] = "First value";
aaa[1] = "Second value";
}
// Processing, e.g. print the 2 input values
System.out.println(aaa[0] + ", " + aaa[1]);
}
}
Fyi, I created a runnable jar using eclipse, and start the application by either
java -jar Test01.jar
or
java -jar Test01.jar arg1 arg2
Hope this helps!
One solution is to change main(String[] args) to get values from env var if they are not present in the passed arguments.
String user;
String password;
if(args.length < 2)
{
user = System.getenv("appUser");
password = System.getenv("appPassword");
} else {
user = args[0];
password = args[1];
}
You can also create another class with a main function that will call the real one.
public class CallerMyApp{
public void main(String[] args) {
String[] realArgs = {System.getenv("appUser"), System.getenv("appPassword")};
MyApp.main(realArgs);
}
}
Then to execute its something like
java -cp myapp.jar CallerMyApp

Passing on command line arguments to runnable JAR [duplicate]

This question already has answers here:
How do I pass parameters to a jar file at the time of execution?
(5 answers)
Closed 5 years ago.
I built a runnable JAR from an Eclipse project that processes a given XML file and extracts the plain text. However, this version requires that the file be hard-coded in the code.
Is there a way to do something like this
java -jar wiki2txt enwiki-20111007-pages-articles.xml
and have the jar execute on the xml file?
I've done some looking around, and all the examples given have to do with compiling the JAR on the command line, and none deal with passing in arguments.
Why not ?
Just modify your Main-Class to receive arguments and act upon the argument.
public class wiki2txt {
public static void main(String[] args) {
String fileName = args[0];
// Use FileInputStream, BufferedReader etc here.
}
}
Specify the full path in the commandline.
java -jar wiki2txt /home/bla/enwiki-....xml
You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.
The command line would be done this way:
c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt
and the java code accesses the value like this:
String context = System.getProperty("myvar");
See this question about argument passing in Java.
You can pass program arguments on the command line and get them in your Java app like this:
public static void main(String[] args) {
String pathToXml = args[0];
....
}
Alternatively you pass a system property by changing the command line to:
java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt
and your main class to:
public static void main(String[] args) {
String pathToXml = System.getProperty("path-to-xml");
....
}
When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

Categories

Resources