I am still a Java newbie and I have this code. I don't know how to pass the input file to the code. I am using Eclipse Juno.
public static void main(String[] args) {
In in = new In(args[0]); // input file
int N = in.readInt(); // N-by-N percolation system
// turn on animation mode
StdDraw.show(0);
// repeatedly read in sites to open and draw resulting system
Percolation perc = new Percolation(N);
draw(perc, N);
StdDraw.show(DELAY);
while (!in.isEmpty()) {
int i = in.readInt();
int j = in.readInt();
perc.open(i, j);
draw(perc, N);
StdDraw.show(DELAY);
}
}
Whenever I run it I get this exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at PercolationVisualizer.main(PercolationVisualizer.java:42)
What might cause this exception? Could you please be patient with me and explain the process of how to call the input file in the code?
Refer to this guide for adding arguments to your program. Alternatively, you could specify the file name directly in the code instead of reading it from the args.
Basically, the guide instructs the user to go to the Run menu, then "Run..." (actually "Run Configurations..." in recent Eclipse versions), select the appropriate run configuration for the desired project, click the Arguments tab, and enter the arguments (such as file name) in the "Program arguments" section, separated by spaces.
For those using IntelliJ you can set the program arguments via Run->Edit Configuration. Look down about the middle of the window to locate the "Program Arguments" field. Then add the path to the test file and save.
Related
I'm on latest Windows 10. I have JDK 15. Latest Visual Studio Code (System). In VS Code, I have half of the Java Extension Pack Installed, i.e Language Support for Java (Red Hat) | Debugger for Java (Microsoft) | Visual Studio IntelliCode (Microsoft). So I did that to just get that run button on the top right (the default installed VS Code didn't have that run button for JAVA programs), below the close button, to that I can run the JAVA programs inside the VS Code. I didn't wanna go out to the directory then open Power Shell or CMD and then write java filename.java and run the program...
Now the issue is that when I click the run button, I think, a Power Shell is opened inside the VS Code and then something other than "java FileName.java" is being written. Because of that I can't really see what the compilation error is. I can only see the line number where the problem is, not actually the solution for that. || If I run the same in the PowerShell outside the VS Code with this "java FileName.java", I can see that there is some issue at x line and also the solution for the same.
So I wanted to know if there is any way to get this type of output inside the Visual Studio Code.
Or if there is any way that Instead of writing a lot of thing like this, we can simple tell the Visual Studio Code to run "java fileName.java" inside VS Code when I click the Run Button at the top.
EDIT:
The Code that I'm running is this one.....
File Name - test.java
import java.io.*;
public class SOPFileTest{
public static void main(String arr[]){
try{
// Creating a File object that represents the disk file.
PrintStream o = new PrintStream(new File("A.txt"));
// Store current System.out before assigning a new value
PrintStream console = System.out;
// Assign o to output stream
System.setOut(o);
System.out.println("Test 1");
// Use stored value for output stream
System.setOut(console);
System.out.println("Test 2");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Now I've noticed somethings, they are:
-When (FileName == Class Name)
---Then (VS Code)
-----Prints the Last System.out.println in the console
-----A.txt is not created / written inside
---Then (Powershell)
-----Prints the Last System.out.println in the console
-----A.txt is created and/or written inside
-When (FileName != Class Name)
---Then (VS Code)
-----shows the error same as the image that I included above.
---Then (Powershell)
-----Prints the Last System.out.println in the console
-----A.txt is created and/or written inside
So powershell works as I intend it would, the VS Code isn't...
If the filename is different from ClassName, java extension will detect it and throws probelms, which is build failed and you can choose if continue:
If you choose proceed, there should be:
[UPDATE -- Screenshot in Powershell:]
It's about the same as problems shown in VS Code.
Java extension requires class must be defined in its own file, so filename should be as the same as ClassName, then everything works well, no matter in integrated Terminal in VS Code, or in the PowerShell outside VS Code:
So I wanted to know if there is any way to get this type of output
inside the Visual Studio Code.
Keeping the filename and classname same makes sure it could be built and compiled successfully, which is the first step.
And the text file should be generated in current working directory, check it in your file explorer.
This question already has answers here:
how to add command line parameters when running java code in Eclipse?
(3 answers)
Closed 9 years ago.
public static void main(String[] args) throws FileNotFoundException, SVGFormatException {
SVG svg = new SVG("test.svg"); //so that the file called test.svg can be called upon
PortablePixmap ppm = new PortablePixmap(500, 500); //select the size of the pixmap(canvas)
svg.drawPixmap(ppm); //draw on ppm
ppm.writeToFile("out.ppm"); //save the file as out.ppm file
This is the code I wrote, but I need to get these values from the command line input because if I hard code like this, the user cannot select what values they want to use. Can you please help me how to get these values from command line input?
Click the little arrow next to the Run button and select run configurations -> (x) = arguments tab and below the Program arguments: text box click the variables button and have at it.
The next time you run your program, a dialog box will prompt you for the arguments.
Now, within your program, you can handle these arguments by parsing the String[] args parameter of the main method.
Command-line arguments are already available to you as the String [] passed to your main() method.
So, if you run your program as
java YourProgram test.svg out.ppm
You can access these arguments as
public static void main(String[] args) throws FileNotFoundException, SVGFormatException {
SVG svg = new SVG(args[0]); // test.svg
PortablePixmap ppm = new PortablePixmap(500, 500);
svg.drawPixmap(ppm); //draw on ppm
ppm.writeToFile(args[1]); // out.ppm
}
Since, you're using Eclipse you would have to go to
Right-click > Run As > Run configurations > Arguments tab
Add test.svg out.ppm under Program arguments. Click Apply and then Run.
I have instruction to run program in command line, for example:
java SetTest < alice30.txt
I wonder how to do this in Eclipse. I tried to put this in Run Configuration like this:
Another thing I don't know is where to put this file (alice30.txt). Is this in root of project or in src folder where source files are located?
I know these are beginner questions but I am stuck and need help.
EDIT:
As #Kane suggested I passed File and opened stream.
Instead of:
Scanner in = new Scanner(System.in);
I now use:
Scanner in = new Scanner(new File("alice30.txt"));
You can pass full file path in arguments (e.g. c:/.../alice30.txt))
The eclipse root directory is the base directory of the project (i.e., not the src/ directory, directly under the project.)
It's generally good style to have a 'resources' folder for txt, graphics, etc.
Rather than trying to pass a stream you could just pass the filename and open the stream yourself.
The reason what you're doing in Eclipse isn't working is because your command prompt/shell/dos/bash/whatever is handling creating the input stream out of the file for you. Eclipse doesn't do this. So, from the command line: < alice.txt means "run this program with no arguments, and create a stream to system.in", while doing that in Eclipse means "run this program with two arguments '<' and 'alice.txt'
you need do like this:
add:
import java.io.IOException;
import java.nio.file.Paths;
then:
replace"Scanner in = new Scanner(System.in);"to"Scanner in =new Scanner(Paths.get("alice30.txt"));" .
and you also need do this : "public static void main(String args[]) throws IOException "
With information from this link/page and several tries, I figure out a way to pass argument and file using the local route in eclipse Run -> Run Configurations.. , though it is not recommended as Kane said.
For my case: I need to do " $java someClass tinyW.txt < tinyT.txt " (This is an example from Algorithms book by Robert Sedgewick)
In my case, " tinyW.txt " is a argument, so in the eclipse environment, you can set in Run -> Run Configurations -> Arguments -> Program arguments: /local address/tinyW.txt. For my Ubuntu: /home/****/tinyW.txt
" < tinyT.txt " is a file that pipe to the main arguments, so you can set the route and file in " Run -> RUn Configurations -> Common ", click the "Input File", use the File System icon and select the file from local compute. See the figure. So in Input File: /local_address/tinyT.txt. My case is: /home/***/tinyT.txt. Hope it also works for you.
I have the following line in a batch file.
java Client "127.0.0.1" 9876
It contains the name of my java class and two arguments. My application requires these arguments to run properly.
Is there any way to pass these arguments when running the application in eclipse? It would make debugging a lot easier. Of course I could resolve the problem by using the values of the arguments in the code but I'm curious.
Instead of just hitting the "Run" icon, select the dropdown box next to it, and choose "Run Configurations". Find your application (or create a Run Configuration for it) and put the command line arguments in the "Arguments" tab. See the docs for more information. It should look like this:
See the run configurations. You can specify arguments. You can even prompt the user for arguments, along with defaults:
${string_prompt:host:127.0.0.1} ${string_prompt:port:9876}
The first prompt is host, with default value 127.0.0.1 filled in. Second pop-up has the prmpt port, with 9876 filled in
Right-click on your project.
Go to Debug As > Debug Configurations or Run As > Run Configurations.
Click the tab that says Arguments.
Enter in your Program Arguments
Click Apply or Debug
Want to add something like, how to add multiple parameters.
Right-click on your project.
Debug > Debug Configurations
Go to Arguments tab.
Enter in your Program Arguments, each separated by a new line. (e.g 3 arguments in attached image)
Click Apply or Debug
Hope it helps.
From "Run" go to debug/run configurations. Click the tab called "Arguments". You can give the program arguments there.
Run configurations > Arguments tab. Just put "127.0.0.1" 9876 in the program arguments.
Run-> Run Configurations->Arguments->Enter your arguments separated by space->Apply->Run
Ensure that the right project name and it's main method are selected under "the Main" tab under run configurations
this work for me, in public static void main method.
public static void main(String argv[]) throws Exception {
int port_com = 2;
boolean debugMode = true;
int socket = 6789;
HasarMain hasarMain = new HasarMain();
// Check if a command line argument exists
if(argv.length != 3){
System.out.println("Missing, Port - socket - debugMode!");
System.exit(0);
}
port_com = Integer.parseInt(argv[0]);
socket = Integer.parseInt(argv[1]);
debugMode = Boolean.parseBoolean(argv[2]);
Run-> Run Configurations->Arguments->Enter your arguments separated by tab->
${string_prompt:argv:"2" "6789" "true"}
I've just started using eclipse and java and I'm not used to either one of them. I wrote a simple helloworld-programm, but the next task (school) was to create a program that takes a userinput (from commandline) and responds with the highest number of two. The code I wrote looks like following:
public class Larger {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
if(args.length < 2)
{
System.out.print("Too few parameters submitted.");
return;
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.print(Math.max(num1, num2));
}
}
It all works well when I hit the "run"-button in eclipse, but later when I browse the source-files and tries to run "java Larger.class 2 4" i get an error from java.exe saying that no class was found.
Any idea what this can be?
When it fails, are you invoking the Java process through Eclipse or the command line? It sounds like you're doing it from the command line. In that case, you don't specify the ".class" portion when invoking your Java program. Try :
java Larger 2 4
The "run" button launch your program with the adequate classpath (the bin folder where the .class is generated)
alt text http://ftp.sumylug.osdn.org.ua/pub/mirrors/eclipse.org/downloads/drops/R-3.2-200606291905/new_noteworthy/images/rt-classpath.png
the java needs to refer to that same bin folder, and use the class name (not the class generated binary)
java -cp bin Larger 2 4
To compile javac Large.java
To run java Larger 2 4