IntelliJ and getting user input - java

so I'm new to using IntelliJ and I've tried googling but to no avail.
I'm creating a simple java program that basically prints hello and gets the user input (name) and prints it... Just to get the ball rolling. Normal Hello World prints fine..
But as soon as I add any [args] in it just crashes? Is there a way I can type the input in?
public class Main {
public static void main(String[] args) {
System.out.println("Hello, " + args[0] + "!");
}
}

You need to provide at least 1 argument if you access args[0] otherwise you get ArrayIndexOutOfBoundsException.
Why ? because the args[] is empty without any arguments passed so accessing the first one will throw the exception
How do you input commandline argument in IntelliJ IDEA?

There's an "edit configurations" item on the Run menu. In that panel, you can create a configuration and then you can choose the Class containing main().
add VM parameters and command-line args, specify the working directory and any environment variables.
you are done.

Sorry guys figured it out:
Go to Run
Edit Configurations > on the left side make sure you're in your Main class or whatever class you're using
Enter what you want in the program arguments. i.e. "James"

Related

How to run java class with custom variables from terminal

My scenario:
I have a Main.java file that simply does System.out.println("Hello").
I run it by first, compiling with javac Main.java and then excecuting the command java Main.
Now what I want is that instead of printing "Hello", it will print whatever the user wants, but I don't want to change the source code whenever I want a different output. So I replaced the System.out.println("Hello") with System.out.println(${MESSAGE}). But this gives error "Cannot resolve symbol MESSAGE".
Ultimately, I want a Main.class file and run with something like java Main -env MESSAGE=whateverIPutHere and it should print out whateverIPutHere.
Is it possible?
You can use system properties
public final class Test {
public static void main(String[] args) {
System.out.println(System.getProperty("port") + " port");
}
}
And then compile and run
javac Test.java
java -Dport=8080 Test
Output is : 8080 port
Now what I want is that instead of printing "Hello", it will print whatever the user wants, but I don't want to change the source code.
Simply not possible without changing code.
System.out.println("Hello")
Prints that string. End of story. And:
System.out.println(${MESSAGE})
is simply not valid Java. If you want to read an environment variable, see here how to do that.
But then: that is really a detour here. You can simply pass arguments on the command line:
java Main "some string" "and another one"
and then retrieve those two strings via the String args[] parameter that your main method receives!
The real answer here: you learn a new language by researching how that language works. You don't assume how syntax might look like, based on experiences from other languages. Meaning: $ENV_VAR is a "shell language" concept. Your idea: "maybe Java has the same" is a very inefficient strategy to go about this.
You can use the input arguments:
public static void main(String[] args) {
System.out.println(args[0]);
}
And then call it like this: java Main whateverIPutHere
Simple as that! args is an array containing all the arguments that you pass in the command line.
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop. The arguments passed in command line is captured by args argument.
class test{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac test.java
run by > java test sonoo jaiswal 1 3 abc
Output:
sonoo
jaiswal
1
3
abc
You can either read it from args as mentioned above, or, if you know how to add a library to your project, try args4j. You'll get way cleaner code as you can use it to separate commandline argument processing to a dedicated class.

AppleScript Can't Get Argument Value Through Terminal

I'm working on a Java GUI and I'm trying to make a button that can start a FaceTime call with a given phone number. Here is an oversimplified version of the java code.
String cellNum = "18001234567";
try {
Runtime.getRuntime().exec("open /Users/faris/Desktop/call.app --args " + cellNum);
} catch (IOException e) {
e.printStackTrace();
}
After researching how do to this, I copied part of an AppleScript app I found online that I named call.app and modified it so it takes in an input argument phone number rather than manually entering it into the script. I've run the program with an actual phone number entered instead of the input variable and it works fine so I know that the problem lies with passing the argument.
call.app
on run args
set input to first item of args
open location "tel://" & input & "?audio=yes"
delay 1
tell application "System Events"
key code 36
end tell
end run
This is the error I get every time from the AppleScript.
Can’t get item 1. (-1728)
I've never used AppleScript before so I'm completely lost currently. Haven't found anything similar anywhere on SO. Any advice would be appreciated very much.
Cause:
Error -1728 in AppleScript is "Can't get «script»", indicating that the first item of args is a script object reference. This means that the command-line argument is not getting passed to your AppleScript's run handler.
Solution:
Instead of saving your AppleScript as an applet, save it (export it) as either a .scpt or an .applescript file. Then substitute your exec(...) Java command for this:
exec("osascript /path/to/applescript " + cellNum);

how to print list of files selected in windows console in java

I have the requirement to print the full path and file names of files selected in windows directory.
the approach I have taken is
1. create key in registry to give option in context menu
2. attached the context menu option to execute my java program
now the issue I have ,
I want to select a few files ,
1. then right click on it
2. then execute my java program
3. and have the list of files selected in my java program as an input
i am not able to achieve point 3
any guidance how to approach it or better alternative
I think there is 2 possible approaches here.
You can custom Send to context menu, it supports passing multiple selected files. I prefer this one. It's quite simple to implement.
For example:
Ex.java
import java.io.IOException;
public class Ex {
public static void main(String[] args)
throws IOException {
for (String argument : args) {
System.out.println(argument);
}
System.in.read();
}
}
Compile it to Ex.class.
Create a shortcut named Test Send To in C:\Users\[username]\AppData\Roaming\Microsoft\Windows\SendTo point to:
"path\to\java.exe" -cp "path\to\Ex.class folder" Ex
Now try selecting multiple files and then right-click Send To > Test Send To, you will see the list of selected files onscreen.
You can implement interprocess communication to tell the existing instance that you want to add more files to proceed.

Using the java System.getProperty("Import")

I was doing some work for college and my main runs this:
Spreadsheet sheet = new Spreadsheet(0,0);
SpreadsheetManager manager = new SpreadsheetManager(sheet);
/* Read an Import file, if any */
String filename = System.getProperty("import");
if (filename != null)
sheet.parseInputFile(filename, sheet);
Thing is, when I actually try to import a file it doesn't do what is supposed to and the filename is always null, so it never reaches my parseInputFile.
My teachers made a bunch of code for different programming exercises that do similar things available, and I've also looked at projects my colleagues did in previous years, but every single one does what I am doing above.
I have to run my program like this: java -Dimport=A-002-002-M-ok.import calc.textui.Calc otherwise none of the tests given by the teachers will run.
I'm sorry if this is not a useful question, but I've tried looking everywhere. If anyone could explain how the System.getProperty("import") works and why it isn't working in this case, I would be very grateful.
I suggest you take a look at the documentation of System.getProperty().
Basically it retrieves a value from the system, either already present or set by you.
To avoid retrieving null you can use another method signature that specify a default value:
System.getProperty("import", "file.txt");
To set a System property, you can specify it at launch:
java -Dimport="file.txt" your_application
or set it programatically :
System.setProperty("import", "file.txt");
When you run your program with:
java -Dimport=foo
then the method call
System.getProperty("import")
should return "foo".
Is ist possible that you write a tiny example program to convince yourself? Without any SheetManagers and all stuff, just
class ItWorks {
public static void main(String[] args) {
System.out.println(System.getProperty("import"));
}
}
Call it thus
java -Dimport=indeed ItWorks
and report what happens.
That being said: if you want to pass command line arguments, why don't you use the facility for command line arguments? (i.e. the String[] array passed to main?)
You could then call your program like this:
java calc.textui.Calc my-nice-spreadsheet.data
=====================================================
Please write the follwoing in your calc.textui.Calc program immediately after the open brace of your class definition:
public class Calc ..... { // a line like this already exists
// insert next line here
public static String filename = System.getProperty("import");
// rest of your class, as before.
}
Then comment out the getProperty() line in your method that didn't work, but leave the rest including the System.out.println(filename);
Does it change?
Maybe system properties are not the most indicated way to do that (depends on your application).
You could also use command line arguments to pass the file name to your main method:
public class CommandLineExample {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("usage: CommandLineExample <filename>");
System.exit(1);
}
String filename = args[0];
if (filename !=null && !filename.isEmpty()) {
...
}
}
}
Your program should be called as:
java CommandLineExample theFileName
the string "theFileName" will be passed to the main method in args[0] (any additional words will be passed in subsequent positions of args {args[1], args[2], ...})
EDIT
if the program must be called with
java -Dimport=filename ...
then System.getProperty("import") will return the filename.
Confirm that you are calling the correct program (class name, package, version, last compile was successful, ...) and also check that the property is not mistyped like java -Dinport=A-... or has additional spaces, uppercase letters...

Send output to program arguments in Java eclipse automatically

In my ANJI (http://anji.sourceforge.net/) java project, I have two java file in package com.anji.neat.
One file names evolver.java which needs one program argument. The output champ-id from evolver.java is to be added as args[1] along with the previous argument fed to evolver.java
How can I add this output to Program Arguments without manually adding it? Plus is it possible that I execute these two java files in one run?
I know the question is complex, but someone kindlu help. I am new to java, so do not get things.
I would suggest that you have main method only in one file, lets say in evolver.java. Add a normal method in your second file which takes two arguments, first argument is the command line argument received in evlover.java and second argument is the champ-id. Run your program by calling the main method of evolver.java. Process the command line argument and generate the champ-id. And after that call the method of your second class by passing both the arguments.
It would become something "ugly" like:
public static void main(String[] args) {
if (args.length == 1) {
String extraArg;
...;
args = new Strinng[] { args[0], nextArg };
// main(args); return;
}
...
}

Categories