How can I get this Java code to run outside of Eclipse?
import java.util.*;
public class Calculations {
public static void main(String[] args) {
Scanner console = new Scanner (System.in);
System.out.println("So... you want to figure out what the Hypotenuse of any Right Triangle is but your to");
System.out.println("lazy to do it your self huh..Sigh... Ok well, At least your being honest about it :)");
System.out.println();
System.out.println("Lets do this...Pythagoreom Style");
System.out.println();
System.out.println("First things first, whats your Sine? And no I don't mean if your an Aquarious or");
System.out.print("some shit like that, I mean your Y value or the first side of your triangle? ");
double side1 = console.nextDouble();
System.out.println();
System.out.println("Okayyyy and now as any good math teacher would say, Whats your Cosine or X value?");
System.out.print("(You might as well learn some Trigonometry while your taking the easy way out) ");
double side2 = console.nextDouble();
System.out.println();
System.out.println("Ok give me a minute... ");
System.out.println();
System.out.println();
System.out.print("Oh, by the way whats your favorite food? ");
String x = console.next();
System.out.println();
System.out.println();
double hypotonuse = Math.sqrt((Math.pow(side1,2)+ Math.pow(side2,2)));
System.out.println("So you favorite food is " + x + " Huh...well...THATS BESIDES THE POINT!!! BACK TO MATH!!!");
System.out.println();
double sum = (Math.pow(side1,2)+Math.pow(side2,2));
System.out.println("So if your First Side is "+side1 + " and we square that and your Second Side is " + side2+ " and we square that too,");
System.out.println();
System.out.println("we can add those sides together to get our sum of "+sum+" Finally we can square root "+sum+ " and Viola!");
System.out.println();
System.out.println("Pythagoras says your Hypotenuse is "+ hypotonuse);
System.out.println();
System.out.println();
System.out.println("HHHAAAZZZAAAAA!!!! FOR MATH!!! HAAAZZZAAAA for Pythagoreum!!!");
System.out.println();
System.out.println();
System.out.println("Oh, and P.S.");
System.out.println();
System.out.println("I'm just kidding, I care about your favorite food,");
System.out.println();
System.out.println("Here's a pyramid type thing of it built by a ratio given by your Hypotenuse :)");
System.out.println();
System.out.println();
for( int i =1; i <=hypotonuse; i++)
{
for (int w = 1; w<=(hypotonuse-i); w++)
{
System.out.print(" ");
}
for(int v=1; v<= (2*i-1); v++)
{
System.out.print(" "+ x );
}
System.out.println();
}
}
}
In Eclipse go to File>Export>java>Runnable jar file>Launch conf pick main class. export dest. destination of file after exporting >finish
after that you can run jar for example with command line(so you can see your console) type cmd in search and run jar by going into your directory where jar is located ..Command for running jar file java -jar nameofjar.jar
Though you can export the class from Eclipse and run it, I would recommend doing it from first principles to understand the process. Later after you understand the basics and work on complex applications, you can use a build tool like ant or maven to generate the jar file and run it.
First principles way:
Ensure you can run java compiler and JVM from command line. You should add your JAVA_HOME/bin to PATH for that to work.
Open command prompt. cd to the directory where you have the Calculations.java file.
Compile the java code by issuing command javac Calculations.java
Compiler generates Calculations.class file in the directory.
You run the compiled class outside Eclipse by issuing command java Calculations. Yes, you don't use .class extension in the command.
If you have multiple class files in a bigger project you can package them into a jar file using command jar -cvf calculations.jar *
It generates calculations.jar file which contains compiled code.
You run the code inside the jar by issuing command java -jar calculations.jar Calculations
Have written this from memory, as I don't have access to eclipse right now.
Right click the project
Export
Executable/Runnable jar file.
(these next 2 steps may be in the wrong order)
Make sure you select the correct class for the main method.
Select the file location and file name
Click done/finish
Browse to your jar, run it
You could always run it from command line
It is answered here and here on stackoverflow with a great detail.
Also you are attempting to run a 'console' applicaiton from jar (which normally doesn't show anything if you execute the jar). You can follow these instructions about how to do it.
Also, though not related to Eclipse IDE, but if you want to experiment netbeans IDE this process is much easy there (Run --> Clean and Build Project) or Shift + F11 automatically creates an executable jar file for the project, located under dist directory.
Related
this is my first time posting here and would like how to solve this error message. It appears only sometimes and only lets me build on a program called Main.java. I'm a begginer programmer so please bear with me, this is the code im trying to run:
import java.util.Scanner;
import java.text.NumberFormat;
public class Main {
public static void main(String[] args) {
Scanner priceScanner = new Scanner(System.in);
System.out.print("Price: ");
int price = priceScanner.nextInt();
Scanner interestScanner = new Scanner(System.in);
System.out.print("Interest rate: ");
double interest = interestScanner.nextDouble();
Scanner numberOfPaymentsScanner = new Scanner(System.in);
System.out.print("Number of payments: ");
int numberOfPayments = numberOfPaymentsScanner.nextInt();
Double monthlyInterest = interest / 1200;
Double result = ((double)price * ((interest * Math.pow((1 +
interest), (double)numberOfPayments))/((Math.pow((1 + interest),
(double)numberOfPayments)) - 1)));
NumberFormat currency = NumberFormat.getCurrencyInstance();
String mortgage = currency.format(result);
System.out.println("Your mortgage is: " + mortgage);
}
}
I haven't seen any comprehensible ways to solve this problem online, and the only thing i think could solve it is to reinstall java in another drive and change the classpath.
Thanks for your attention.
I solved it - my mistake. While executing the program using the terminal I was typing java Main.java, whereas the correct execution method was to type java Main.
With Single-file source-code programs which is a new way of executing 1 File Java programs is only available since Java 11. You can run the command:
java (Java File Name without .java extension)
java Main.java
Though please take into consideration that this way of executing only works if your Java project is only 1 Java File.
FYI:
This single-file source code will be executed fully in memory and you can only import code that came with the JDK you are working.
Finally if you want your code to run as fast as possible compile with javac before executing you program.
javac Main.java
java Main
Just be careful that there is no Main.class already in the folder, this may cause a confusion to the compiler.
Step 1:
javac + Filename.java
Step 2:
java + Filename // execute without add .java
I just started learning JAVA and Sublime Text 3 was proposed to me as a great compiler for JAVA code. I downloaded it, started programming and set my build system as JavaC. I wanted to create a quick program adding two numbers given by the user and displaying the result but nothing comes up in the "build" section. Do you have any idea to make that work ?
Here is the code I wanna try:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int a,b;
Scanner input=new Scanner(System.in);
System.out.println("Enter a number:");
a=input.nextInt();
System.out.println("Enter a number:");
b=input.nextInt();
System.out.println("sum=" + (a+b));
}
}
For future references on how this windows command line or command prompt in windows works.
First check if your computer have the JRE (required to run a Java program) and JDK ( required compile and run Java programs) already install to verify this input the text "java -version" and javac -version into the Command Line. If the Javac is already intalls, however, doesn't show in the command line then you need to follow this sites on how to set up the path depending on your OS.
I want to use openalpr in my java project. What must I include to use the API? What libs must be imported in project properties in Eclipse or Netbeans?
I found the solution
Download openalpr binaries
https://github.com/openalpr/openalpr/releases
Install and configure jdk (java and javac path)
Compile openalpr java source code, start java_test.bat file
Start main.java
java -classpath java Main "us" "openalpr.conf" "runtime_data" "samples/us-1.jpg"
Copy the native libs (DLLs for windows) into the exec dir
Copy the java classes into your project (dir: /src/main/java)
Get started with:
`
Alpr alpr = new Alpr("us", "/path/to/openalpr.conf", "/path/to/runtime_data");
// Set top N candidates returned to 20
alpr.setTopN(20);
// Set pattern to Maryland
alpr.setDefaultRegion("md");
AlprResults results = alpr.recognize("/path/to/image.jpg");
System.out.format(" %-15s%-8s\n", "Plate Number", "Confidence");
for (AlprPlateResult result : results.getPlates())
{
for (AlprPlate plate : result.getTopNPlates()) {
if (plate.isMatchesTemplate())
System.out.print(" * ");
else
System.out.print(" - ");
System.out.format("%-15s%-8f\n", plate.getCharacters(), plate.getOverallConfidence());
}
}
(Source: http://doc.openalpr.com/bindings.html#java)
Dear fellow java enthusiast,
I would like to make my java program into a executable .jar file with the help of eclipse. I exported into a .jar file but when I double click it it does not seem to work? I think i am missing something but after some time trying to find how to do it i cant find it.
Any advice?
import java.util.Scanner;
public class GravityMoon {
public static void main(String[] args) {
System.out.println("Please enter your earthweight in kilograms below:");
Scanner earthweight = new Scanner(System.in);
// Repeat until next item is a double
while (!earthweight.hasNextDouble())
{
// Read and discard offending non-double input
earthweight.next();
// Re-prompt
System.out.print("Please enter your earthweight "
+ "in numerical kilograms: ");
}
double moonweight;
// Converts earthweight in moonweight 17%
moonweight = earthweight.nextDouble() * 0.17;
// convert to whole numbers
//closes keyboard input
earthweight.close();
//prints out your moonweight in a decimal number
System.out.println("Your moonweight is " + Math.round(moonweight * 100d) /100d
+ " kilograms.");
}}
as you did not explain the exact problem, I might only give hints:
Export as Executable Jar
In Eclipse, there is the option to export into a jar file and another option to export into an executable jar file (see http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-37.htm).
(I guess you are using windows) Try to execute the jar file from the console (something like java -jar ).
Double klicking a jar file in windows does not open a terminal window.
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.