This question already has answers here:
The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (...)
(4 answers)
Closed 5 years ago.
I'm doing a intro to programming course and I'm having issues with my Eclipse that doesn't seem to want to run printf in even its simplest form.
My code is:
package Practice;
import java.io.*;
public class Printf {
public static void main(String[] args) throws IOException
{
int num1 = 54;
int num2 = 65;
int sum = num1 + num2;
System.out.printf("Sum of %d and %d is %d.", num1, num2, sum);
}
}
The error is as saying
The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, int, int, int)
I have the Java compiler compliance level set to 1.8 so it should have no issues as I have read in previous posts. Kepler version of Eclipse has had the Java 8 patch applied (so I could comply with 1.8)
No site I have found has given me any other clues as to what the issue could be?
Turns out the project folders in Eclipse run on their own properties seperate from the Eclipse main settings .. in order for them to compile on version 1.6/1.7/1.8 you have to change their properties seperatly from the main settings...
Basically instead of going to windows > preferances ... to change and update the compiler version you right click on the project folder in Package Explorer > Properties > Java Compiler then check the Enable project specific settings and then Change the settings below to the compiler compliance level of 1.5 or higher in order for this code above to work.
Why it does that i have no idea makes no sence but it at least works now :)
Try using System.out.format("Sum of %d and %d is %d.", num1, num2, sum); instead of printf
right click on project folder -> properties -> java compiler -> mark(Enable project specific settings) -> set compiler compliance level : 1.6 -> enjoy eclipse
Related
I am setting up a java framework that should use the Google OR-Tools. The code below compiles successfully, but throws an exception at runtime:
Exception in thread "main" java.lang.UnsatisfiedLinkError: com.google.ortools.linearsolver.operations_research_linear_solverJNI.MPSolver_CLP_LINEAR_PROGRAMMING_get()I
at com.google.ortools.linearsolver.operations_research_linear_solverJNI.MPSolver_CLP_LINEAR_PROGRAMMING_get(Native Method)
at com.google.ortools.linearsolver.MPSolver$OptimizationProblemType.<clinit>(MPSolver.java:221)
at Main.main(Main.java:15)
I am using Intellij 2018.3 on Windows 10. I spent a lot of time trying to get this run, but unsuccessful. Based on what I found on the internet, the exception might be caused by poor linking and/or missing external libraries on which OR-Tools depends. However, I don't have the background to resolve this issue, and also Intellij does not highlight anything. Any idea what the problem is?
For completion, this is the code I run:
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
public final class Main {
public static void main(String[] args) {
// Create the linear solver with the GLOP backend.
MPSolver solver =
new MPSolver("SimpleLpProgram", MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING);
// Create the variables x and y.
MPVariable x = solver.makeNumVar(0.0, 1.0, "x");
MPVariable y = solver.makeNumVar(0.0, 2.0, "y");
System.out.println("Number of variables = " + solver.numVariables());
// Create a linear constraint, 0 <= x + y <= 2.
MPConstraint ct = solver.makeConstraint(0.0, 2.0, "ct");
ct.setCoefficient(x, 1);
ct.setCoefficient(y, 1);
System.out.println("Number of constraints = " + solver.numConstraints());
// Create the objective function, 3 * x + y.
MPObjective objective = solver.objective();
objective.setCoefficient(x, 3);
objective.setCoefficient(y, 1);
objective.setMaximization();
solver.solve();
System.out.println("Solution:");
System.out.println("Objective value = " + objective.value());
System.out.println("x = " + x.solutionValue());
System.out.println("y = " + y.solutionValue());
}
}
In my case solution was simple - I just needed to add this singe line of code:
Loader.loadNativeLibraries();
where loader comes from com.google.ortools.Loader
Disclaimer: more a long comment than an answer...
note: I supposed you are using the github repository of or-tools if you used the binary package it should be more or less the same...
1) You must load the jni library which will load the OR-Tools C++ libraries and its dependencies...
/** Simple linear programming example.*/
public class Main {
static {
System.loadLibrary("jniortools");
}
public static void main(String[] args) throws Exception {
2) Did you manage to run the java samples ?
make run SOURCE=ortools/linear_solver/samples/SimpleLpProgram.java
ref: https://developers.google.com/optimization/introduction/java#simple_example
3) As Kayaman pointed out, you must pass the folder where the java runtime can find the native libraries (i.e. the JNI wrapper jniortools.dll and its dependencies libortools.dll)
if you look at the console log you'll see the full command line:
java -Xss2048k -Djava.library.path=lib -cp lib\sample.jar;lib\com.google.ortools.jar;lib\protobuf.jar ...\sample
Which comes from, the makefiles/Makefile.java file:
JAVAFLAGS = -Djava.library.path=$(LIB_DIR)
...
ifeq ($(SOURCE_SUFFIX),.java) # Those rules will be used if SOURCE contain a .java file
$(CLASS_DIR)/$(SOURCE_NAME): $(SOURCE) $(JAVA_OR_TOOLS_LIBS) | $(CLASS_DIR)
-$(DELREC) $(CLASS_DIR)$S$(SOURCE_NAME)
-$(MKDIR_P) $(CLASS_DIR)$S$(SOURCE_NAME)
"$(JAVAC_BIN)" -d $(CLASS_DIR)$S$(SOURCE_NAME) \
-cp $(LIB_DIR)$Scom.google.ortools.jar$(CPSEP)$(LIB_DIR)$Sprotobuf.jar \
$(SOURCE_PATH)
...
.PHONY: run # Run a Java program.
run: build
"$(JAVA_BIN)" -Xss2048k $(JAVAFLAGS) \
-cp $(LIB_DIR)$S$(SOURCE_NAME)$J$(CPSEP)$(LIB_DIR)$Scom.google.ortools.jar$(CPSEP)$(LIB_DIR)$Sprotobuf.jar \
$(SOURCE_NAME) $(ARGS)
endif
src: https://github.com/google/or-tools/blob/46173008fdb15dae1dca0e8fa42a21ed6190b6e4/makefiles/Makefile.java.mk#L15
and
https://github.com/google/or-tools/blob/46173008fdb15dae1dca0e8fa42a21ed6190b6e4/makefiles/Makefile.java.mk#L328-L333
note: you can run make detect_java to know the flags i.e. value of LIB_DIR
note: if you did use the precompiled package the Makefile is here:
https://github.com/google/or-tools/blob/stable/tools/Makefile.cc.java.dotnet
Then after you can try to add this option in Intellij...
You must understand that or-tools is a set of C++ native libraries which are wrapped to Java using the SWIG generator.
To make it work using Intellij (over a windows machine) you need to:
Install Microsoft Visual C++ Redistributable for Visual Studio
Download and extract the OR-Tools library for Java
In intellij, add jar dependency to the 2 jars under the lib folder of the extracted files (each of the 2 jars separately, do not add to lib folder itself. This is why).
Add the lib library path to VM options. In Intellij edit your run-configuration and add to vm options: -Djava.library.path=<path to the lib folder that hold the jars>
Load the jni library statically by adding the below code to your class (as mentioned here.)
static {
System.loadLibrary("jniortools");
}
I have this Java code:
public class Calc {
public int quotient(int a, int b){
return a/b;
}
}
and TestNG unit test for this method:
#Test ()
public void testingMethod3() {
Assert.assertEquals(0, calc.quotient(5,0));
}
On my work computer I successfully get
java.lang.ArithmeticException: / by zero
message, as expected.
But when my colleague runs this test on home computer, then mentioned exception is not throwing and test passes.
How this magic could occur?
P.S.
Environment
OS: Windows 10
TestNG version: 6.13.1
Java version: 8 (don't know exact build version)
P.P.S.
Deletion of target folder and rebuilding of the project was that very helpful solution. Seem like IDE cashed old project sources, and didn't flush them after changes in the code.
In the past, I experienced something like yours. Because different JDK compile environment and/or JRE runtime environment. And need check the different of version of TestNG.
check by add few line of code to print Java properties.
Properties p = System.getProperties();
Enumeration keys = p.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = (String)p.get(key);
System.out.println(key + ": " + value);
}
then comparing
Below is the code:
class PlayWithBinary {
static int age;
public static void main (String args[]){
int i = 0b10101010;
System.out.println("my age is: " + age + " my salary is: "+ i);
}
}
In terminal I executed : javac PlayWithBinary.java
For some reasons it is showing this error message:
PlayWithBinary.java:5: ';' expected
int i = 0b10101010;
^
1 error
Any ideas?
Update: for those who are getting similar errors, here is the link to download JDK 8 - Java SE Development Kit 8 Downloads
Make sure your project is configured with a Java compliance level of Java 7 or above, or you could modify your code to use Integer.parseInt(String, int) like
int i = Integer.parseInt("10101010", 2);
It sounds like you're using an older version of Java that doesn't support this. This feature was added in Java 7 - see the documentation and this related question. You should upgrade your Java version to fix this.
Alternatively, you can use Integer.parseInt(String, int) on your code: int i = Integer.parseInt("10101010", 2);
This question already has answers here:
How to enable the Java keyword assert in Eclipse program-wise?
(6 answers)
Closed 8 years ago.
I am checking if number is between 1-10 using assert, but if I enter a number beyond 10 it still gives me the result rather than throwing an exception. What am I doing wrong?
import java.util.Scanner;
public class xina {
public static void main(String[] args) throws Exception {
System.out.println("enter any number");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
assert ( num >= 0 && num <= 10 ) : "bad number: " + num;
System.out.println("You entered " + num);
}
}
Assertions are disabled by default in java. You need to manually enable them by adding -ea to your command-line arguments when you invoke the java compiler. I can't tell you how to do this without knowing what compiler/environment you're using.
Edit:
In eclipse, go to the run menu, and click on run configurations. Select the arguments tab and type -ea into the VM arguments.
Are assertions enabled (-ea flag when running program) ?
By default, they are not enabled by the virtual machine.
This article shows you how to do it in eclipse. Could be helpful for you
Go to Run->run configuration
select java application in left nav pan.
right click and select New.
select Arguments tab
Add -ea in VM arguments.
How to enable the Java keyword assert in Eclipse program-wise?
I have a very bad experienced about the scanner because I am using GUI and JOptionPane. So I am not be able to do the program's interns of scanner because. I am new to it so Please help me, "cannot find the scanner". This is my code so far .
import java.io.*;
import java.util.*;
class MultiplicationTables{
public static void main(String args[]){
int n, c;
System.out.println("Enter an integer to print its multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of "+n+" is :-");
for ( c = 1 ; c <= 10 ; c++ )
System.out.println(n+"*"+c+" = "+(n*c));
}
}
If your Java is not version 1.5 or above, Scanner class is not provided.
go to command promt
type "java -version"
check your version.If you have outdated just update. Problem shoud be fixed..
and make sure your IDE or the JDK actually use it.
Code that you have here provided is correct so you can use it after you fix your problem.
First import is redundant.
import java.io.*; // you can remove it
Scanner is a class in java.util package.
Check weather you have properly set your jdk path in your ide, or in your system.
Depends on system that you use:
Windows: Advanced System Settings->Environment Variables->Path check weather there is your path to jdk.
UNIX in console print 'echo $PATCH' and check that if you have there jdk path properly added.
And then you can check your version of java independent to system in console writing
java --version