How to run a Java Class in Terminal - java

I have done a lot of research and, I could not find how to solve my problem. I saw that there are a lot of people who ask this question, but still none of them answered it for me.
I am a beginner at java and I made a simple calculator in Eclipse.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner numInput = new Scanner(System.in);
double fnum, snum;
String operation;
System.out.println("First number: ");
fnum = numInput.nextDouble();
System.out.println("Second number: ");
snum = numInput.nextDouble();
Scanner oper = new Scanner(System.in);
System.out.println("Please select one of the following operations: ");
System.out.println("+");
System.out.println("-");
System.out.println("/");
System.out.println("*");
operation = oper.next();
switch (operation){
case "+":
System.out.println("Your answer is: " + (fnum + snum));
break;
case "-":
System.out.println("Your answer is: " + (fnum - snum));
break;
case "*":
System.out.println("Your answer is: " + (fnum * snum));
break;
case "/":
System.out.println("Your answer is: " + (fnum / snum));
break;
}
}
}
Later I went into the Workspace folder to find the Calculator.class file.
I opened terminal and typed:
Danylo-RIB:~ mac$ java /Users/mac/Documents/workspace/Calculator/bin/Calculator.class
I followed all the instructions on how to run a class in MacOs Terminal, but all I got for an answer in my terminal instead of my program was:
Danylo-RIB:~ mac$ java /Users/mac/Documents/workspace/Calculator/bin/Calculator.class
Error: Could not find or load main class .Users.mac.Documents.workspace.Calculator.bin.Calculator.class
Danylo-RIB:~ mac$
So my question is, how do I do this? How do I run a class in Terminal?
EDIT: Okay, thanks to the people who answered my question!

cd into the directory in which your Calculator.java file is stored, run
javac Calculator.java
this will create a file Calculator.class. You can now run the compiled class with
java Calculator
mind that there is no .class to be added!

The online docs should be your first recourse:
https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html
which tell us that the command line is
java [options] classname [args]
In more depth, and linked from somewhere on that page, you can read
https://docs.oracle.com/javase/8/docs/technotes/tools/unix/classpath.html#CBHHCGFB
which is applicable to pretty much all the Java tools. These docs contain the answer to your question. You can either cd into the directory that is the root of your classpath and use the default classpath, as one answer suggested, or use the classpath options described in the docs to set the directory(-ies) at the top of your classpath. E.g.,
java -cp /Users/mac/Documents/workspace/Calculator/bin Calculator

Just follow these simple steps:
From Terminal install open jdk
sudo apt-get install openjdk-7-jdk
Write a java program and save the file as filename.java.
Now to compile use this command from the terminal:
javac filename.java
If everything works well, then a new filename.class file should be created.
To run your program that you've just compiled type the command below in terminal:
java filename

From Command Line:
>javac Calculator.java
It will generate Calculator.class file.
Then
>java Calculator
Run the program if it finds the main method.
(Java Environment variable should be set and must execute it from the folder where Calculator.java is kept.)
If you're using eclipse, then simply hit the Play button from the eclipse tool bar.
I hope this helps.

An alternative way is to create a runnable .jar file.
First, you need to export jar file for the class. You can do this by right clicking to the .java file. Then Export > Runnable Jar file as in the picture.
Next step is to run it on the terminal by java -jar your_runnable_jar_file.jar.

Related

Can't run Oracle suggested JAVA code in Eclipse [duplicate]

This question already has answers here:
System.console() returns null
(13 answers)
Closed 5 years ago.
I'm trying to learn Regular Expressions in JAVA, it was suggested I copy and compile code in my preferred IDE (Eclipse) to test how the API works.
Source: https://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html
When I run, my IDE simply says "No Console" in the output.
I've written many programs from the online classes I've been taking for JAVA, never encountering a situation where the console is not recognized. I have exported those compiled projects as runnable .jars and never had a problem from the command line executing only the jar file name. I have found when exporting as a runnable .jar - for this specific jar file - to preface executing on the command line with --> java -jar <*runnable.jar*>.
That works ... running from my IDE does not.
Perhaps obviously, I'm a newbie to OOP, and I've searched everywhere (including on your site), and don't have a clue. I am running the Mars 2 (4.5.2) version of Eclipse on a Windows 7 64-bit machine; JRE/JDK 8; along with a JAVA_HOME ENV setup.
Can someone give me an idea as to which properties to change in the IDE settings for Eclipse? Or perhaps, the Oracle code needs to be augmented for my particular environment?
This tutorial uses System.console(), but this requires an actual terminal, and that won't work when running in an IDE. That's a shame because it could very well read from System.in & print to System.out instead.
Here is a replacement that will work in Eclipse or any good IDE:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTestHarness {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("\nEnter your regex: ");
Pattern pattern =
Pattern.compile(input.nextLine());
System.out.println("Enter input string to search: ");
Matcher matcher =
pattern.matcher(input.nextLine());
boolean found = false;
while (matcher.find()) {
System.out.printf("I found the text" +
" \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());
found = true;
}
if(!found){
System.out.println("No match found.\n");
}
}
}
}

I compile and then run this bit of code in java.exe and i receive an error

I can't seem to figure out what is wrong with this code. Eclipse tells me main method isn't declared. and when I run it in java.exe it tells me "could not find or load main class discount.java" I've spent the last half hour looking for a solution but can't seem to figure it out.
import java.util.Scanner;
public class Discount
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int price;
System.out.println("Enter the Price:");
price = scan.nextInt();
System.out.println( price / 4 * 3 );
}
}
The commands I'm using and error I'm getting:
> CD C:\Programing\Misc
> set path=%path%;C:\Program Files\Java\jdk1.8.0\bin
> javac discount.java
> java discount.java
Error: Could not find out or load main class java.discount
Are you using java discount.java? That's likely the issue.
Try these two lines:
javac discount.java
java discount
That should run your main method (assuming that you've correctly named the file discount.java).
--
EDIT: After seeing your comment about changing the class name, you'll want to rename the file to Discount.java. Then run javac Discount.java and java Discount
The filename has to match the classname exactly, so put this in the file Discount.java (discount.java won't work).
Then, from my command-line:
% javac Discount.java
% java Discount
Enter the Price:
^C
Have a look at this file hierarchy and how to compile java on command line

Make a Java application run itself from the command prompt?

I have an executable Jar file and to keep it simple, I want to make it so that you can simply double click it on the desktop and it will run. I've tried this:
if(args.length == 0){
String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar \"" + decodedPath + "\" -arg");
System.out.println("java -jar \"" + decodedPath + "\" -arg");
}
To no avail. I assumed that if I told the program to check for the "-arg" argument and it wasn't there, then it would asssume the program was run from the executable, not being called from the command line. So is there a way to make the program open a command prompt and then run itself within it, killing the previous program?
As to "run on double click", this is OS dependent.
You can "run a jar" at the command line using:
java -jar the.jar
This requires that the jar has a META-INF/MANIFEST.MF and that this manifest file has a Main-Class entry, the argument being the class where your main() method is. For instance:
Main-Class: org.foobar.mypackage.Foo
What I have done for a similar problem is that I have made a separate GUI program in a JAR file with some JTextFields for input and a JButton for confirmation. When the button gets clicked, it calls the main method in my other class with those values in a String array to start that program and close the GUI form with frame.setVisible(false). I suggest doing something like that, but it's dependent on what type of program you're developing.
You could also just pass the necessary command-line flags directly into the JRE at runtime! I just figured this out a couple weeks ago, but you can access the java.library.path and change it to match necessary library paths through reflection by just putting this code in the front of your main method.
try{
System.setProperty("java.library.path", path);
Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );
}catch(Exception ex){
// just exit and tell user that there was an error or something similar
}
Anyway, I hope that this was helpful. You can also do many similar things by similar code.

Java application only works when launched via a terminal/command prompt

I'm recently starting to learn Java and have had success writing and compiling my own application (written in Sublime Text, a text editor, and compiled via javac).
The application runs perfectly when launched via a terminal (or command prompt if I'm on my Windows PC), but if I try launching it from the file itself (in Windows, double clicking it and ensuring Java is the open-with method, or on my Ubuntu laptop, making it executable and doing the same) I get a very short lived loading cursor and then nothing.
The application (which converts between degrees Celsius and Fahrenheit) uses some simple Swing dialogs to get the user's input and to display the result.
import javax.swing.*;
public class DegreesConversion
{
public static void main( String [] args)
{
String input = JOptionPane.showInputDialog("Enter a temperature followed by either C for Celcius or F for Fahrenheit\nE.g. 30C or 86F");
int degrees = Integer.parseInt(input.substring(0,input.length()-1));
switch (input.toLowerCase().contains("f") ? 0 : input.toLowerCase().contains("c") ? 1 : 2){
case 1:
JOptionPane.showMessageDialog(null,(((degrees*9)/5)+32)+" degrees Fahrenheit", "Conversion complete", JOptionPane.INFORMATION_MESSAGE);
break;
case 0:
JOptionPane.showMessageDialog(null,(((degrees-32)*5)/9)+" degrees Celcius","Conversion complete",JOptionPane.INFORMATION_MESSAGE);
break;
default:
JOptionPane.showMessageDialog(null, "The input you entered was not recognised!","Unknown input", JOptionPane.ERROR_MESSAGE);
break;
}
}
}
(This is by no means meant to be a serious or terribly functional application, it was simply my own attempt at making something in Java)
Anyhow, I'm not sure why this application, when compiled, only functions when launched from a CLI using "java DegreesConversion", and not when launched through a double click. I have looked for answers regarding this on Google and Stackoverflow, but haven't found anything near a relevant solution or hint as to why this is so.
I'm considering that Java .class files can't be executed the same as .jars?
Any assistance would be greatly appreciated!
Package your class into a jar file and add a manifest to it pointing to the class having the main method you like to execute.
Then you can do java -jar jarFile.jar from terminal but it is also possible to easily to run it through, e.g., Windows Open-With capabilities.
EDIT:
JAR tutorial

Scanner cannot be resolved to a type

I just installed Ubuntu 8.04 and I'm taking a course in Java so I figured why not install a IDE while I am installing it. So I pick my IDE of choice, Eclipse, and I make a very simple program, Hello World, to make sure everything is running smoothly. When I go to use Scanner for user input I get a very odd error:
My code:import java.util.Scanner;
class test {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("hi");
}
}
The output:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type
Scanner cannot be resolved to a type
at test.main(test.java:5)
The Scanner class is new in Java 5. I do not know what Hardy's default Java environment is, but it is not Sun's and therefore may be outdated.
I recommend installing the package sun-java6-jdk to get the most up-to-date version, then telling Eclipse to use it.
If you are using a version of Java before 1.5, java.util.Scanner doesn't exist.
Which version of the JDK is your Eclipse project set up to use?
Have a look at Project, Properties, Java Build Path -- look for the 'JRE System Library' entry, which should have a version number next to it.
It could also be that although you are have JDK 1.5 or higher, the project has some specific settings set that tell it to compile as 1.4. You can test this via Project >> Properties >> Java Compiler and ensure the "Compiler Compliance Level" is set to 1.5 or higher.
I know, It's quite a while since the question was posted. But the solution may still be of interest to anyone out there. It's actually quite simple...
Under Ubuntu you need to set the java compiler "javac" to use sun's jdk instead of any other alternative. The difference to some of the answers posted so far is that I am talking about javac NOT java. To do so fire up a shell and do the following:
As root or sudo type in at command line:
# update-alternatives --config javac
Locate the number pointing to sun's jdk, type in this number, and hit "ENTER".
You're done! From now on you can enjoy java.util.Scanner under Ubuntu.
System.out.println("Say thank you, Mr.");
Scanner scanner = java.util.Scanner(System.in);
String thanks = scanner.next();
System.out.println("Your welcome.");
You imported Scanner but you're not using it. You're using Scanner, which requires user inputs. You're trying to print out one thing, but you're exposing the your program to the fact that you are going to use your own input, so it decides to print "Hello World" after you give a user input. But since you are not deciding what the program will print, the system gets confused since it doesn't know what to print. You need something like int a=sc.nextInt(); or String b=sc.nextLine(); and then give your user input. But you said you want Hello World!, so Scanner is redundant.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input seconds: ");
int num = in.nextInt();
for (int i = 1; i <=num; i++) {
if(i%10==3)
{
System.out.println(i);
}
}
}
}

Categories

Resources