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");
}
}
}
}
Related
This question already has answers here:
How to clear the console?
(14 answers)
Closed last year.
I'm curious to know how to clear the console in Windows. I tried a few command, but nothing works
Runtime.getRuntime().exec("cls");
This didn't work for me.
I'd like to know if there is any method to clear the terminal in Java or if there is an external library to do this.
The link in answer by #Olivier does work but unfortunately most suggestions use a sub-process cls or don't explain how to enable on Windows.
In latest Windows 10 you can use ANSI code support in Window Terminal, but not directly in CMD.EXE consoles. To enable for CMD.EXE add the registry key VirtualTerminalLevel mentioned in these answers for ANSI colours and then you can print the appropriate ANSI/VT codes directly without running a sub-process:
System.out.print("\033[2J\033[1;1H");
Or
System.out.print(ANSI.CLEAR_SCREEN+ANSI.position(1, 1));
where simple definition of ANSI codes is:
public class ANSI {
// Control Sequence Introducer:
public static String CSI = "\u001b[";
public static String CLEAR_SCREEN = CSI+"2J";
public static String position(int row, int col) {
return CSI+row+";"+col+"H";
}
}
Note that other terminals or such as those in IDEs may not support the above.
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.
I want to use JOMP API (equivalent to OpenMP in C) but I met some problems:
This is the code I want to run:
import jomp.runtime.*;
public class Hello
{
public static void main (String argv[])
{
int myid;
//omp parallel private(myid)
{
myid = OMP.getThreadNum();
System.out.println("Hello from " + myid);
}
}
}
It is just an hello worl but I have a problem with the compiler. Please have a quick look at this page to understand:
http://www2.epcc.ed.ac.uk/computing/research_activities/jomp/download.html
But I can't, I do not understand how it works... I can only compile it with eclipse default compiler (I guess) and then I have only one thread!
I understand I have to compile this code (in a .jomp file) with
java jomp.compiler.Jomp MyFile
and then compile normally but I can't do this in ecplise neither in the terminal (I do not know how to install this compiler!)
ps: I use Ubuntu 12.04 on a Intel® Core™ i7-3610QM CPU # 2.30GHz × 8.
You just need to add the JOMP parameters to your launch configuration, this example can help you:
JOMP eclipse workaround
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
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);
}
}
}
}