Compiling and running a simple Java program using java-algs4 - java

I'm learning Java through the this Princeton course https://algs4.cs.princeton.edu/home/. I've create a simple Java program called Ortho.java using the Java provided by the course (that I installed using this tutorial: https://algs4.cs.princeton.edu/linux/). The program receives two .txt input files, it reads those as a list of strings, and print their first value.
Here's the program:
package edu.princeton.cs.algs4;
import java.util.Arrays;
class Ortho{
public static void main(String args[]){
// Read files from input and print statements
In in = new In(args[0]);
String[] list = in.readAllStrings(); //parse the first text input
while (!StdIn.isEmpty()) {
String key = StdIn.readString();
System.out.print(key);
}
}
}
I run this command on the shell to compile my program, this creates a file called Ortho.class:
javac-algs4 Ortho.java
This is the command I use to run the program:
java-algs4 Ortho.class text_1.txt < text_2.txt
But I always get this error:
Error: Could not find or load main class Ortho.class
Caused by: java.lang.ClassNotFoundException: Ortho.class
What do I need to do to properly compile and run this program with the algs4 Java lib provided by the course?
This is my project structure:
dir/
Ortho.java
Ortho.class
text_1.txt
text_2.txt

Run the program like this :
java algs4.Ortho text_1.txt < text_2.txt
Let me know if this worked for you or no.

Related

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 can I pass variables from the command prompt into my java program

Is there a way to read data from the command prompt? I have a java program that relies on 4 input variables from an outside source. These variables are returned to the command prompt after I run a javascript program but i need a way to pass these variables from the command prompt into my java program, any help would be greatly appreciated!
While executing java program pass the parameters and all the parameters should be separated by space.
java programName parameter1 parameter2 parameter3 parameter4
This parameters would be available in your main method argument
public static void main(String[] args){
//This args array would be containing all four values, i.e. its length would be 4 and you easily iterate values.
for(int i=0; i<args.length; i++){
System.out.println("Argument " + i + " is " + args[i]);
}
Follow the link:
Command-Line Arguments - The Java™ Tutorials : https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
shared by #BackSlash.
It has all the content which would help you to clear all your doubts.
The content from the link is quoted below:
Displaying Command-Line Arguments passed by user from command-line to a Java program
The following example displays each of its command-line arguments on a
line by itself:
public class DisplayCommandLineParameters {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
To compile the program: From the Command Prompt, navigate to the directory containing your .java file, say C:\test, by typing the cd
command below.
C:\Users\username>cd c:\test
C:\test>
Assuming the file, say DisplayCommandLineParameters.java, is in the
current working directory, type the javac command below to compile it.
C:\test>javac DisplayCommandLineParameters.java
C:\test>
If everything went well, you should see no error messages.
To run the program: The following example shows how a user might run the class.
C:\test>java DisplayCommandLineParameters Hello Java World
Output:
Hello
Java
World
Note that the application displays each word — Hello, Java and World —
on a line by itself. This is because the space character separates
command-line arguments.
To have Hello, Java and World interpreted as a single argument, the
user would join them by enclosing them within quotation marks.
C:\test>java DisplayCommandLineParameters "Hello Java World"
Output: Hello Java World

How to read and write text files from the main in java

The static method main, which receives an array of strings. The array should have two elements: the path where the files are located (at index 0), and the name of the files to process (at index 1). For example, if the name was “Walmart” then the program should use “Walmart.cmd” (from which it will read commands) and “Walmart.pro” (from which it will read/write products).
I don't want anyone to write the code for me because this is something I need to learn. However I've been reading this through and the wording is confusing. If someone could help me understand what it wants from me through pseudo-code or an algorithm it would be greatly appreciated.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
The main method's String array input argument consists of whatever String arguments you pass to the program's main method when you run the program. For example, here is a simple program that loops over args and prints a nice message with each argument's index and value on a separate line:
package com.example;
public class MainExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.printf("args[%d]=%s\n", i, args[i]);
}
}
}
Once you've compiled the program, you can run it on the command-line and pass it some arguments:
java -cp . com.example.MainExample eh? be sea 1 2 3 "multiple words"
Output:
args[0]=eh?
args[1]=be
args[2]=sea
args[3]=1
args[4]=2
args[5]=3
args[6]=multiple words
So lets explain to you
Create a class Inventory : if you don't know how to create a class google it just as is
The static method main: Every executable class in java (at least from the console) has the main method you should google java main method and propably in the same place you find it you will see the default arguments that it receives
When you learn about the default arguments of method main you will undertand about the 'args' that has to be on it
You will have t study the class String google it "java String class"
You will have to study the class File google it "java File class"
At the end everything else would be just logic and I beleave you have learned some at this point.
public class Inventory { // class inventory
public static void main(String[] args) // main method
{
if(args.length==2){ // check if args contains two elements
String filePath = args[0];
String fileName = args[1];
filePath+= System.getProperty("file.separator")+fileName;
File fileCMD = new File(filePath+".cmd");
//fileCMD.createNewFile();
File filePRO =new File(filePath+".pro");
//filePRO.createNewFile();
}
else {
//write the code to print the message Usage: java Inventory Incorrect number of parameters for a while and exit the program.
}
}
This is what I've understood. Basically you have to write a program to create two files, one called fileName.cmd and the other fileName.pro. You have to construct the path of the files using the arguments (input parameters of the main method) and system's file separator. If the arguments don't have two elements you have to print the 'invalid' message. That's it.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
You have to use command line to pass the arguments and launch the program , something like the following code in cmd or terminal:
java inventory thePath theFileName
That's how it get initialized.

String[] args parameter: java.lang.ArrayIndexOutOfBoundsException

Hi i am a java learner and trying to make this program for add two number.
While running this i am getting this error msg..
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at addnumber.main(addnumber.java:16)
Java Result: 1
public class addnumber{
public static void main(String[] args) {
String x,y;
int a,b,c;
x=args[0];
y=args[1];
a=Integer.parseInt(x);
b=Integer.parseInt(y);
c=a+b;
System.out.println(c);
}
}
I know i can use Scanner class or string builder class however whats wrong with this code?
If you use the args-array you have to give the programm some parameters from outside for example from the console.
So open the console and go to the directory where the .java file is and compile it manually with
javac Addnumber.java
Now you should see a .class file there.
Than write a call like this:
java Addnumber 5 9
your arguments would be 5 and 9.
Also write the classname in capitals
If your running with eclipse or any other working tool. then you have to set run configuration-arguments.
Suppose you run this code in command line then you have to run this code using the below command
java addnumber 2 4
Good Quastion, The Problem is in String[] args, this problem leads to find out what is the initial value of this Parameter as string? or in other words How is the IDEs call the main method? if you run this code in Netbeans or Eclipse by default will print this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
because by default the IDE call method with array of string with 0 length:
TheNameOfClass.main(new String[0]) // if you run it in some IDEs
>java Addnumber // cmd with no args?
In your case the exception will occur in line x=args[0]; because you invoke and you want to use some item in array out of range or grater than the length of the array.
Now you can configure it as example in eclipse to pass some Strings values as you need OR you need to compile and run the java class manual in a 'Command Prompt' and passed some of Strings values:
>javac Addnumber.java // compile it
>java Addnumber 1 77 // run it and passs some values to array in main method

run class file as separate process from java code

public static void main(String args[]) throws IOException
{
Process p = Runtime.getRuntime().exec("java E:/workspace/JNIProgram/src/JNIProgram.class");
}
so I have this code and am trying to run the JNIProgram.class file however the program gets terminated instantly without doing its job (which is to create a new txt file and write to it)
So what am I doing wrong
The java command expects a Java class name, not a filename.
So the command java E:/workspace/JNIProgram/src/JNIProgram.class is wrong. If you try this manually from a command prompt window you'll get an error message.
The command should be something like this:
java -cp E:\workspace\JNIProgram\src JNIProgram
Note: What's after the -cp option is the classpath, and after that the fully-qualified class name (which is just JNIProgram, if the class is not in a package).
First make sure that you can run the command manually from the command line before you make it work from another Java program.

Categories

Resources