I got the below code from the following website bridge connection between R and Java using Rcaller
http://www.mhsatman.com/rcaller.php
Running it under NETBEANS IDE on Windows shows the following warning:
Note:C:\Users\aman\Documents\NetBeansProjects\JavaApplicationRCaller\src\javaapplicationrcaller\JavaApplicationRCaller.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
But it also shows this and not printing the results i.e.
rcaller.exception.RCallerExecutionException: Can not run C:\Program Files\R\R-
3.0.1\bin\i386\Rscript. Reason: java.io.IOException: Cannot run program
"C:\Program": CreateProcess error=2, The system cannot find the file specified
This is the RScript executable code path:
C:\Program Files\R\R-3.0.1\bin\i386\Rscript
package javaapplicationexample;
import rcaller.RCaller;
import java.util.Random;
public class JavaApplicationExample {
public static void main(String[] args) {
new JavaApplicationExample();
}
public JavaApplicationExample(){
try{
/*
* Creating Java's random number generator
*/
Random random = new Random();
/*
* Creating RCaller
*/
RCaller caller = new RCaller();
/*
* Full path of the Rscript. Rscript is an executable file shipped with R.
* It is something like C:\\Program File\\R\\bin.... in Windows
*/
// It is showing the same error when writing Rscript.exe here
caller.setRscriptExecutable("C:\\Program Files\\R\\R-3.0.1\\bin\\i386\\Rscript");
/* We are creating a random data from a normal distribution
* with zero mean and unit variance with size of 100
*/
double[] data = new double[100];
for (int i=0;i<data.length;i++){
data[i] = random.nextGaussian();
}
/*
* We are transferring the double array to R
*/
caller.addDoubleArray("x", data);
/*
* Adding R Code
*/
caller.addRCode("my.mean<-mean(x)");
caller.addRCode("my.var<-var(x)");
caller.addRCode("my.sd<-sd(x)");
caller.addRCode("my.min<-min(x)");
caller.addRCode("my.max<-max(x)");
caller.addRCode("my.standardized<-scale(x)");
/*
* Combining all of them in a single list() object
*/
caller.addRCode("my.all<-list(mean=my.mean, variance=my.var, sd=my.sd, min=my.min, max=my.max, std=my.standardized)");
/*
* We want to handle the list 'my.all'
*/
caller.runAndReturnResult("my.all");
double[] results;
/*
* Retrieving the 'mean' element of list 'my.all'
*/
results = caller.getParser().getAsDoubleArray("mean");
System.out.println("Mean is "+results[0]);
/*
* Retrieving the 'variance' element of list 'my.all'
*/
results = caller.getParser().getAsDoubleArray("variance");
System.out.println("Variance is "+results[0]);
/*
* Retrieving the 'sd' element of list 'my.all'
*/
results = caller.getParser().getAsDoubleArray("sd");
System.out.println("Standard deviation is "+results[0]);
/*
* Retrieving the 'min' element of list 'my.all'
*/
results = caller.getParser().getAsDoubleArray("min");
System.out.println("Minimum is "+results[0]);
/*
* Retrieving the 'max' element of list 'my.all'
*/
results = caller.getParser().getAsDoubleArray("max");
System.out.println("Maximum is "+results[0]);
/*
* Retrieving the 'std' element of list 'my.all'
*/
results = caller.getParser().getAsDoubleArray("std");
/*
* Now we are retrieving the standardized form of vector x
*/
System.out.println("Standardized x is ");
for (int i=0;i<results.length;i++) System.out.print(results[i]+", ");
}catch(Exception e){
System.out.println(e.toString());
}
}
}
This is the final answer:
I solved the error by using and installing the following (I should mention it here for others):
install.packages("Runiversal",repos="cran.r-project.org")
and then:
install.packages("Runiversal")
In regard to your error, this is caused by a space in the path to the R executable. You could try escaping the space (caller.setRscriptExecutable("C:\\Program\ Files\\R\\R-3.0.1\\bin\\i386\\Rscript"); (note the extra \ before the space). Or you could simply reinstall R to a path that does not include a space (e.g. c:\\R). This last solution is the most robust.
RCaller 2.2 does not require problematic Runiversal package. Visit the blog entry for details here.
Related
I have a rather complex MILP, but the main problem is the number of continuous variables, not the number of binaries. I just "hard-coded" the linear relaxation to understand its output, and it takes approx. 10-15 minutes to solve (which is not extremely surprising). If I run the MILP with outputs, I don't see anything happening for the first 10 minutes, because it takes those 10 minutes to construct a first integer-feasible solution. So it would help to be able to enable the same outputs I am seeing when solving the linear relaxation "manually" (so something like Iteration: 1 Dual objective = 52322816.412592) within the B&B output.
Is this possible? I googled at bit, but I only found solutions for steering the solution algorithm, or for deriving linear relaxations using callbacks, while I am interested in a "simple" output of the intermediate steps.
It sounds like you are asking for extra detailed logging during the linear relaxation part of the solve during the B&B. Have a look at the CPLEX parameter settings like IloCplex.Param.MIP.Display (try setting this to 5) and also IloCplex.Param.Simplex.Display (try setting to 1 or 2).
within java you could rely on IloConversion objects that will allow you to locally change the type of one or more variables.
See the sample AdMIPex6.java
/* --------------------------------------------------------------------------
* File: AdMIPex6.java
* Version 20.1.0
* --------------------------------------------------------------------------
* Licensed Materials - Property of IBM
* 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
* Copyright IBM Corporation 2001, 2021. All Rights Reserved.
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with
* IBM Corp.
* --------------------------------------------------------------------------
*
* AdMIPex6.java -- Solving a model by passing in a solution for the root node
* and using that in a solve callback
*
* To run this example, command line arguments are required:
* java AdMIPex6 filename
* where
* filename Name of the file, with .mps, .lp, or .sav
* extension, and a possible additional .gz
* extension.
* Example:
* java AdMIPex6 mexample.mps.gz
*/
import ilog.concert.*;
import ilog.cplex.*;
public class AdMIPex6 {
static class Solve extends IloCplex.SolveCallback {
boolean _done = false;
IloNumVar[] _vars;
double[] _x;
Solve(IloNumVar[] vars, double[] x) { _vars = vars; _x = x; }
public void main() throws IloException {
if ( !_done ) {
setStart(_x, _vars, null, null);
_done = true;
}
}
}
public static void main(String[] args) {
try (IloCplex cplex = new IloCplex()) {
cplex.importModel(args[0]);
IloLPMatrix lp = (IloLPMatrix)cplex.LPMatrixIterator().next();
IloConversion relax = cplex.conversion(lp.getNumVars(),
IloNumVarType.Float);
cplex.add(relax);
cplex.solve();
System.out.println("Relaxed solution status = " + cplex.getStatus());
System.out.println("Relaxed solution value = " + cplex.getObjValue());
double[] vals = cplex.getValues(lp.getNumVars());
cplex.use(new Solve(lp.getNumVars(), vals));
cplex.delete(relax);
cplex.setParam(IloCplex.Param.MIP.Strategy.Search,
IloCplex.MIPSearch.Traditional);
if ( cplex.solve() ) {
System.out.println("Solution status = " + cplex.getStatus());
System.out.println("Solution value = " + cplex.getObjValue());
}
}
catch (IloException e) {
System.err.println("Concert exception caught: " + e);
}
}
}
if you use OPL then you could have a look at Relax integrity constraints and dual value
int nbKids=300;
float costBus40=500;
float costBus30=400;
dvar int+ nbBus40;
dvar int+ nbBus30;
minimize
costBus40*nbBus40 +nbBus30*costBus30;
subject to
{
ctKids:40*nbBus40+nbBus30*30>=nbKids;
}
main {
var status = 0;
thisOplModel.generate();
if (cplex.solve()) {
writeln("Integer Model");
writeln("OBJECTIVE: ",cplex.getObjValue());
}
// relax integrity constraint
thisOplModel.convertAllIntVars();
if (cplex.solve()) {
writeln("Relaxed Model");
writeln("OBJECTIVE: ",cplex.getObjValue());
writeln("dual of the kids constraint = ",thisOplModel.ctKids.dual);
}
}
I have a small code example I want to include in the Javadoc comment for a method.
/**
* -- ex: looping through List of Map objects --
* <code>
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get("wordID"));
* System.out.println(map.get("word"));
* }
* </code>
*
* #param query - select statement
* #return List of Map objects
*/
The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.
-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }
Parameters
query - - select statement
Returns:
List of Map objects
I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ?
In addition to the already mentioned <pre> tags, you should also use the #code JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:
* <pre>
* {#code
* Set<String> s;
* System.out.println(s);
* }
* </pre>
Will give correct HTML output:
Set<String> s;
System.out.println(s);
While omitting the #code block (or using a <code> tag) will result in HTML like this:
Set s;
System.out.println(s);
For reference, a full list of tag descriptions available in Java SE 8 can be found here.
I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:
usage of old <code> - tag to prevent the curly brackets from being interpreted
usage of "new" {#code ...} - tag to get the generics included in the output
escaping of the # sign in #Override via "{#literal #}Override" because javadoc generator "tilts" there due to the fact that the # goes directly after an opening curly bracket
remove one space in front of {#code and {#literal, to compensate inner spaces and keep the alignment
javadoc code:
/** this methods adds a specific translator from one type to another type. `
* i.e.
* <pre>
* <code>new BeanTranslator.Builder()
* .translate(
* new{#code Translator<String, Integer>}(String.class, Integer.class){
* {#literal #}Override
* public Integer translate(String instance) {
* return Integer.valueOf(instance);
* }})
* .build();
* </code>
* </pre>
* #param translator
*/
gets printed as
new BeanTranslator.Builder()
.translate(
new Translator<String, Integer>(String.class, Integer.class){
#Override
public Integer translate(String instance) {
return Integer.valueOf(instance);
}})
.build();
The java source has lots of good examples for this. Here's an example from the head of "String.java":
....
* is equivalent to:
* <p><blockquote><pre>
* char data[] = {'a', 'b', 'c'};
* String str = new String(data);
* </pre></blockquote><p>
* Here are some more examples of how strings can be used:
* <p><blockquote><pre>
* System.out.println("abc");
* String cde = "cde";
* System.out.println("abc" + cde);
* String c = "abc".substring(2,3);
* String d = cde.substring(1, 2);
* </pre></blockquote>
...
Enclose your multiline code with <pre></pre> tags.
You need the <pre></pre> tags for the line breaks, and the {#code ... } inside them for generics. But then it's not allowed to place the opening brace on the same line as the <generic> tag, because then everything will be displayed on 1 line again.
Displays on one line:
* ..
* <pre>
* {#code
* public List<Object> getObjects() {
* return objects;
* }
* </pre>
* ..
Displays with line breaks:
* ..
* <pre>
* {#code
* public List<Object> getObjects()
* {
* return objects;
* }
* </pre>
* ..
Another weird thing is when you paste the closing brace of {#code, it gets displayed:
* ..
* <pre>
* {#code
* public List<Object> getObjects()
* {
* return objects;
* }
* }
* </pre>
* ..
Output:
public List<Object> getObjects()
{
return objects;
}
}
/**
* <blockquote><pre>
* {#code
* public Foo(final Class<?> klass) {
* super();
* this.klass = klass;
* }
* }
* </pre></blockquote>
**/
<pre/> is required for preserving lines.
{#code must has its own line
<blockquote/> is just for indentation.
public Foo(final Class<?> klass) {
super();
this.klass = klass;
}
UPDATE with JDK8
The minimum requirements for proper codes are <pre/> and {#code}.
/**
* test.
*
* <pre>{#code
* <T> void test(Class<? super T> type) {
* System.out.printf("hello, world\n");
* }
* }</pre>
*/
yields
<T> void test(Class<? super T> type) {
System.out.printf("hello, world\n");
}
And an optional surrounding <blockquote/> inserts an indentation.
/**
* test.
*
* <blockquote><pre>{#code
* <T> void test(Class<? super T> type) {
* System.out.printf("hello, world\n");
* }
* }</pre></blockquote>
*/
yields
<T> void test(Class<? super T> type) {
System.out.printf("hello, world\n");
}
Inserting <p> or surrounding with <p> and </p> yields warnings.
Here's my two cents.
As the other answers already state, you should use <pre> </pre> in conjuction with {#code }.
Use pre and {#code}
Wrapping your code inside <pre> and </pre> prevents your code from collapsing onto one line;
Wrapping your code inside {#code } prevents <, > and everything in between from disappearing. This is particularly useful when your code contains generics or lambda expressions.
Problems with annotations
Problems can arise when your code block contains an annotation. That is probably because when the # sign appears at the beginning of the Javadoc line, it is considered a Javadoc tag like #param or #return. For example, this code could be parsed incorrectly:
/**
* Example usage:
*
* <pre>{#code
* #Override
* public void someOverriddenMethod() {
Above code will disappear completely in my case.
To fix this, the line must not start with an # sign:
/**
* Example usage:
*
* <pre>{#code #Override
* public int someMethod() {
* return 13 + 37;
* }
* }</pre>
*/
Note that there are two spaces between #code and #Override, to keep things aligned with the next lines. In my case (using Apache Netbeans) it is rendered correctly.
I was able to generate good looking HTML files with the following snip-it shown in Code 1.
* <pre>
* {#code
* A-->B
* \
* C-->D
* \ \
* G E-->F
* }
*</pre>
(Code 1)
Code 1 turned into the generated javadoc HTML page in Fig 1, as expected.
A-->B
\
C-->D
\ \
G E-->F
(Fig. 1)
However, in NetBeans 7.2, if you hit Alt+Shift+F (to reformat the current file), Code 1 turns in to Code 2.
* <
* pre>
* {#code
* A-->B
* \
* C-->D
* \ \
* G E-->F
* }
* </pre>
(Code 2)
where the first <pre> is now broken onto two lines. Code 2 produces generated javadoc HTML file as shown in Fig 2.
< pre> A-->B \ C-->D \ \ G E-->F
(Fig 2)
Steve B's suggestion (Code 3) seems to give the best results and remains formatted as expected even after hitting Alt+Shift+F.
*<p><blockquote><pre>
* A-->B
* \
* C-->D
* \ \
* G E-->F
* </pre></blockquote>
(Code 3)
Use of Code 3 produces the same javadoc HTML output as shown in Fig 1.
Since Java 18 (JEP 413) you may use #snippet tag:
/**
* -- ex: looping through List of Map objects --
* {#snippet :
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get("wordID"));
* System.out.println(map.get("word"));
* }
* }
*
* #param query - select statement
* #return List of Map objects
*/
There is a significant difference between <blockquote><pre>... and <pre>{#code.... The former will omit the type declarations in generics but the latter will keep it.
E.g.:
List<MyClass> myObject = null;
displays as List myObject = null; with the firts and as List<MyClass> myObject = null; with the second
I just read the Javadoc 1.5 reference here, and only the code with <and > must be enclosed inside {#code ...}. Here a simple example:
/**
* Bla bla bla, for example:
*
* <pre>
* void X() {
* List{#code <String>} a = ...;
* ...
* }
* </pre>
*
* #param ...
* #return ...
*/
.... your code then goes here ...
A combination of two of the other solutions seems perfect:
* <pre>{#code
* {#literal #}Override
* public void someMethod() {
* Set<String> s;
* }
* }</pre>
ie. use <pre>{#code to start and }</pre> to end the snippet. Also, replace # with {#literal #}.
Haven't found an easier solution. Quite sad for a language that has been under active development for decades.
If you are Android developer you can use:
<pre class=”prettyprint”>
TODO:your code.
</pre>
To pretty print your code in Javadoc with Java code.
Try replacing "code" with "pre". The pre tag in HTML marks the text as preformatted and all linefeeds and spaces will appear exactly as you type them.
I work through these two ways without any problem:
<pre>
<code>
... java code, even including annotations
</code>
</pre>
and
<pre class="code">
... java code, even including annotations
</pre>
Of course the latter is more simplest and observe the class="code" part
I enclose my example code with <pre class="brush: java"></pre> tags and use SyntaxHighlighter for published javadocs. It doesn't hurt IDE and makes published code examples beautiful.
Using Java SE 1.6, it looks like all UPPERCASE PRE identifiers is the best way to do this in Javadoc:
/**
* <PRE>
* insert code as you would anywhere else
* </PRE>
*/
is the simplest way to do this.
An Example from a javadoc I got from a java.awt.Event method:
/**
* <PRE>
* int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
* int offmask = CTRL_DOWN_MASK;
* if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
* ...
* }
* </PRE>
*/
This produces output that looks exactly like the regular code, with the regular code spacings and new lines intact.
In Visual Studio Code at least, you can force a Javadoc comment to respect line-breaks by wrapping it in triple-backticks, as seen below:
/** ```markdown
* This content is rendered in (partial) markdown.
*
* For example, *italic* and **bold** text works, but [links](https://www.google.com) do not.
* Bonus: it keeps single line-breaks, as seen between this line and the previous.
``` */
I am doing my first Java assignment and I'm struggling with an error here.
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ctof;
/**
*
* #author Braydon
*/
import java.util.Scanner;
public class CtoF {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter temperature in Celsius:");
Scanner temp = new Scanner(System.in);
String T = scan.nextLine();
T = (T - 32) * 5/9;
System.out.println("Temperature in Fahrenheit =" + T);
}
}
The error it gives me is as follows.
run:
Enter temperature in Celsius:
Exception in thread "main" java.lang.UnsupportedOperationException: Not supported yet.
at ctof.scan.nextLine(scan.java:19)
at ctof.CtoF.main(CtoF.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
The error is in the line where I perform the math, but I've tried everything and I can't seem to fix it. Please help!
You're calling the wrong function.
You need to call temp.nextLine() instead of scan.nextLine() in order to read the next line. (scan isn't even defined in the code you posted)
HOWEVER: You shouldn't use nextLine() when you need to read a number.
Therefore: Call temp.nextInt() or temp.nextDouble() instead.
I believe you are newbie to java. First of all, you will have to learn about the data types. Well, you can google basics about programming and learn from it.
The solution for your problem :
public class CtoF {
public static void main(String[] args) {
System.out.println("Enter temperature in Celsius:");
Scanner temp = new Scanner(System.in);
int T = temp.nextInt();
T = (T - 32) * 5 / 9;
System.out.println("Temperature in Fahrenheit =" + T);
}
}
Try to use good names for the variables (just a suggestion)
I am currently trying to Design and implement a stringed musical instrument class.
The instructions for this assignment are:
Data fields for your instrument should include number of strings, an array of string names representing string names (e.g. E,A,D,G),
boolean fields to determine if the instrument is tuned, and if the instrument is currently playing. You are welcome to add additional data fields if you like.
A constructor method that set the tuned and currently playing fields to false.
Other methods 1) to tune the instrument,
to start the instrument playing, and 3) to stop the instrument from playing.
Other methods as you see fit (Add at least one unique method).
That is the main file, I then have to:
create a Java test class that simulates using your instrument class. In your test class be you should at a minimum: a) Construct 10 instances of your instrument,
b) tune your instruments,
c) Start playing your instrument,
d) Call your unique method, and
e) Stop playing your instruments.
(Hint: Arrays and Loops will make your job easier and result in more efficient code!)
I have created both files but my main project file has some issues that prevent me from seeing an output when I test it. (I’m using netbeans to test the program if that helps at all.)
My current test file has no errors but I know that is necessary for the outputs to print on the main java file so I also attached that as well.
here is my main project java file:
import java.io.*;
/* File: KenMasonp3.java
* Author: Kenneth Mason
* Date: 19-04-2014
* Purpose: Design and implement a stringed musical instrument class
* Code edited/modified by myself with sources from LEO classroom modules, Liang
* book, javaprogrammingforums.com, dreamincode.net, and the instructor
*/
public class KenMasonp3 { // start main class
// start main method
public static void main(String[] args) throws IOException {
//creates a file named from the command line argument
File outputFile = new File(args[0]);
PrintWriter output = new PrintWriter(outputFile);
//creates an array of 10 objects
instrument[] guitarArray = new instrument[10];
/*calls methods to construct, tune, play,
*get the string names and stop the instrument array
*/
instrument.constructGuitarArray(guitarArray, output);
instrument.tuneGuitar(guitarArray, output);
instrument.playGuitar(guitarArray, output);
instrument.getStrings(guitarArray, output);
instrument.stopGuitar(guitarArray, output);
//close the file
output.close();
} // main method end
} // end main class
// Guitar class
class instrument {
//method to construct the instrument array
public static instrument[] constructGuitarArray(instrument[] array,
PrintWriter file) {
//creates a random instrument
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
error is:
* " constructor instrument in class instrument cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length "
*/
array[i] = new instrument((int) (1 + Math.random() * 12));
//prints the creation message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable createdMessage
* location: class instrument
*/
file.println(array[i].createdMessage);
}
//returns array to main method
return array;
}
//method that calls the tune method for the instrument array
public static void tuneGuitar(instrument[] array,
PrintWriter file) {
//tunes all objects in the array
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method
* location: class instrument
*/
array[i].setTune(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
*error is: cannot find symbol variable tunedMessage
* location: class instrument
*/
file.println(array[i].tunedMessage);
}
}
//method that calls the play method for the instrument array
public static void playGuitar(instrument[] array, PrintWriter file) {
//plays all objects in the array
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method setPlay(boolean)
* location: class instrument
*/
array[i].setPlay(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable playMessage
* location: class instrument
*/
file.println(array[i].playMessage);
}
}
//method that calls the getStrings method for the instrument array
public static void getStrings(instrument[] array, PrintWriter file) {
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method setString(boolean)
* location: class instrument
*/
array[i].setString(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable stringMessage
* location: class instrument
*/
file.println(array[i].stringMessage);
}
}
//method that calls the stopGuitar method for the instrument array
public static void stopGuitar(instrument[] array, PrintWriter file) {
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method setStop(boolean)
* location: class instrument
*/
array[i].setStop(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable stopMessage
* location: class instrument
*/
file.println(array[i].stopMessage);
}
}
Note: file outputFile = new File(args[0]);
because I need to write the output from your Instrument class methods to a text file that a user entered from the command line arguments
If you can see, my main problem seems to be this line of code:
array[i] = new instrument((int) (1 + Math.random() * 12));
The error says in netbeans:
" constructor instrument in class instrument cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length "
I think it's because of this error that I'm getting cannot find symbol on many of my other parts of code.
If anyone needs my text file it is here (but has no apparent errors):
/* File: KenMasonp3.java
* Author: Kenneth Mason
* Date: 19-04-2014
* Purpose: Design and implement a stringed musical instrument class
* Code edited/modified by myself with sources from LEO classroom modules, Liang
* book, javaprogrammingforums.com, dreamincode.net
*/
public class KenMasonp3test { // start main class
public static void main(String[] args) {
}
//instrument class
class guitarInstrument {
//private variable declarations
private boolean tuned, playing;
private String guitarType;
private String[] stringNames;
//public variable declarations
public String playMessage, tunedMessage, createdMessage;
public StringBuilder guitarStringsNames;
//default constructor that generates a random 6 string instrument
public guitarInstrument() {
int strings = (int) (1 + Math.random() * 12);
//generates array based on number of strings
String[] stringNames = new String[strings];
//fills string array with random string names
for (int i = 0; i < stringNames.length; i++) {
stringNames[i] = String.valueOf((char)('A' + Math.random() *
('G' - 'A' + 1)));
}
this.stringNames = stringNames;
//sets instrument name
guitarType = "random " + strings + "-string instrument";
//sets tuned and playing to false
tuned = false;
playing = false;
//sets string for construction of the instrument
createdMessage = "You created a " + guitarType;
} // end of guitar() method
//constructor allowing specific amount of strings
public guitarInstrument(int strings) {
//creates specific instrument based on number of strings input
if (strings == 6) {
//creates and fills string array
String[] stringNames = {"E", "A", "D", "G", "B", "E"};
this.stringNames = stringNames;
//names instrument
guitarType = "guitar";
} // end if
else {
//creates and fills string array
String[] stringNames = new String[strings];
//fills array with random string names
for (int i = 0; i < stringNames.length; i++) {
stringNames[i] = String.valueOf((char)('A' + Math.random()
* ('G' - 'A' + 1)));
}
this.stringNames = stringNames;
//names instrument
guitarType = strings + "-string instrument";
} // end else
//sets tuned and playing to false
tuned = false;
playing = false;
//sets string for construction of the instrument
createdMessage = "You created a " + guitarType;
} // end guitar (in strings) method
//method to tune or untune the instrument
public void setTune(boolean tune) {
this.tuned = tune;
//sets string for tuned instrument
if (tuned == true) {
tunedMessage = "The " + guitarType + " is now in tune";
} // end tuned if
//sets string for untuned instrument
else {
tunedMessage = "The " + guitarType + " is out of tune";
} // end of tuned else
} // end of setTune method
//method to play or stop the instrument
public void playGuitarInstrument(boolean play) {
this.playing = true;
// sets string for playing instrument
if (playing == true) {
playMessage = "The" + guitarType + "is now playing";
} // end playing if
// sets string for unplayed instrument
else {
playMessage = "The" + guitarType + "has stopped";
} // end play else
} // end of playGuitarInstrument method
//method to display the string names of the instrument
public void getStrings() {
//sets stringbuilder with default intro statement
StringBuilder guitarStringNames = new StringBuilder();
System.out.println("The has the following strings:"
+ guitarStringNames);
} // end of getString method
} // end of guitarInstrument method
} // end of main class
Any help would be greatly appreciated.
new instrument((int) (1 + Math.random() * 12));
This line has your problem. instrument does not have a constructor which takes an integer as a parameter.
I have a small code example I want to include in the Javadoc comment for a method.
/**
* -- ex: looping through List of Map objects --
* <code>
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get("wordID"));
* System.out.println(map.get("word"));
* }
* </code>
*
* #param query - select statement
* #return List of Map objects
*/
The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.
-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }
Parameters
query - - select statement
Returns:
List of Map objects
I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ?
In addition to the already mentioned <pre> tags, you should also use the #code JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:
* <pre>
* {#code
* Set<String> s;
* System.out.println(s);
* }
* </pre>
Will give correct HTML output:
Set<String> s;
System.out.println(s);
While omitting the #code block (or using a <code> tag) will result in HTML like this:
Set s;
System.out.println(s);
For reference, a full list of tag descriptions available in Java SE 8 can be found here.
I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:
usage of old <code> - tag to prevent the curly brackets from being interpreted
usage of "new" {#code ...} - tag to get the generics included in the output
escaping of the # sign in #Override via "{#literal #}Override" because javadoc generator "tilts" there due to the fact that the # goes directly after an opening curly bracket
remove one space in front of {#code and {#literal, to compensate inner spaces and keep the alignment
javadoc code:
/** this methods adds a specific translator from one type to another type. `
* i.e.
* <pre>
* <code>new BeanTranslator.Builder()
* .translate(
* new{#code Translator<String, Integer>}(String.class, Integer.class){
* {#literal #}Override
* public Integer translate(String instance) {
* return Integer.valueOf(instance);
* }})
* .build();
* </code>
* </pre>
* #param translator
*/
gets printed as
new BeanTranslator.Builder()
.translate(
new Translator<String, Integer>(String.class, Integer.class){
#Override
public Integer translate(String instance) {
return Integer.valueOf(instance);
}})
.build();
The java source has lots of good examples for this. Here's an example from the head of "String.java":
....
* is equivalent to:
* <p><blockquote><pre>
* char data[] = {'a', 'b', 'c'};
* String str = new String(data);
* </pre></blockquote><p>
* Here are some more examples of how strings can be used:
* <p><blockquote><pre>
* System.out.println("abc");
* String cde = "cde";
* System.out.println("abc" + cde);
* String c = "abc".substring(2,3);
* String d = cde.substring(1, 2);
* </pre></blockquote>
...
Enclose your multiline code with <pre></pre> tags.
You need the <pre></pre> tags for the line breaks, and the {#code ... } inside them for generics. But then it's not allowed to place the opening brace on the same line as the <generic> tag, because then everything will be displayed on 1 line again.
Displays on one line:
* ..
* <pre>
* {#code
* public List<Object> getObjects() {
* return objects;
* }
* </pre>
* ..
Displays with line breaks:
* ..
* <pre>
* {#code
* public List<Object> getObjects()
* {
* return objects;
* }
* </pre>
* ..
Another weird thing is when you paste the closing brace of {#code, it gets displayed:
* ..
* <pre>
* {#code
* public List<Object> getObjects()
* {
* return objects;
* }
* }
* </pre>
* ..
Output:
public List<Object> getObjects()
{
return objects;
}
}
/**
* <blockquote><pre>
* {#code
* public Foo(final Class<?> klass) {
* super();
* this.klass = klass;
* }
* }
* </pre></blockquote>
**/
<pre/> is required for preserving lines.
{#code must has its own line
<blockquote/> is just for indentation.
public Foo(final Class<?> klass) {
super();
this.klass = klass;
}
UPDATE with JDK8
The minimum requirements for proper codes are <pre/> and {#code}.
/**
* test.
*
* <pre>{#code
* <T> void test(Class<? super T> type) {
* System.out.printf("hello, world\n");
* }
* }</pre>
*/
yields
<T> void test(Class<? super T> type) {
System.out.printf("hello, world\n");
}
And an optional surrounding <blockquote/> inserts an indentation.
/**
* test.
*
* <blockquote><pre>{#code
* <T> void test(Class<? super T> type) {
* System.out.printf("hello, world\n");
* }
* }</pre></blockquote>
*/
yields
<T> void test(Class<? super T> type) {
System.out.printf("hello, world\n");
}
Inserting <p> or surrounding with <p> and </p> yields warnings.
Here's my two cents.
As the other answers already state, you should use <pre> </pre> in conjuction with {#code }.
Use pre and {#code}
Wrapping your code inside <pre> and </pre> prevents your code from collapsing onto one line;
Wrapping your code inside {#code } prevents <, > and everything in between from disappearing. This is particularly useful when your code contains generics or lambda expressions.
Problems with annotations
Problems can arise when your code block contains an annotation. That is probably because when the # sign appears at the beginning of the Javadoc line, it is considered a Javadoc tag like #param or #return. For example, this code could be parsed incorrectly:
/**
* Example usage:
*
* <pre>{#code
* #Override
* public void someOverriddenMethod() {
Above code will disappear completely in my case.
To fix this, the line must not start with an # sign:
/**
* Example usage:
*
* <pre>{#code #Override
* public int someMethod() {
* return 13 + 37;
* }
* }</pre>
*/
Note that there are two spaces between #code and #Override, to keep things aligned with the next lines. In my case (using Apache Netbeans) it is rendered correctly.
I was able to generate good looking HTML files with the following snip-it shown in Code 1.
* <pre>
* {#code
* A-->B
* \
* C-->D
* \ \
* G E-->F
* }
*</pre>
(Code 1)
Code 1 turned into the generated javadoc HTML page in Fig 1, as expected.
A-->B
\
C-->D
\ \
G E-->F
(Fig. 1)
However, in NetBeans 7.2, if you hit Alt+Shift+F (to reformat the current file), Code 1 turns in to Code 2.
* <
* pre>
* {#code
* A-->B
* \
* C-->D
* \ \
* G E-->F
* }
* </pre>
(Code 2)
where the first <pre> is now broken onto two lines. Code 2 produces generated javadoc HTML file as shown in Fig 2.
< pre> A-->B \ C-->D \ \ G E-->F
(Fig 2)
Steve B's suggestion (Code 3) seems to give the best results and remains formatted as expected even after hitting Alt+Shift+F.
*<p><blockquote><pre>
* A-->B
* \
* C-->D
* \ \
* G E-->F
* </pre></blockquote>
(Code 3)
Use of Code 3 produces the same javadoc HTML output as shown in Fig 1.
Since Java 18 (JEP 413) you may use #snippet tag:
/**
* -- ex: looping through List of Map objects --
* {#snippet :
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get("wordID"));
* System.out.println(map.get("word"));
* }
* }
*
* #param query - select statement
* #return List of Map objects
*/
There is a significant difference between <blockquote><pre>... and <pre>{#code.... The former will omit the type declarations in generics but the latter will keep it.
E.g.:
List<MyClass> myObject = null;
displays as List myObject = null; with the firts and as List<MyClass> myObject = null; with the second
I just read the Javadoc 1.5 reference here, and only the code with <and > must be enclosed inside {#code ...}. Here a simple example:
/**
* Bla bla bla, for example:
*
* <pre>
* void X() {
* List{#code <String>} a = ...;
* ...
* }
* </pre>
*
* #param ...
* #return ...
*/
.... your code then goes here ...
A combination of two of the other solutions seems perfect:
* <pre>{#code
* {#literal #}Override
* public void someMethod() {
* Set<String> s;
* }
* }</pre>
ie. use <pre>{#code to start and }</pre> to end the snippet. Also, replace # with {#literal #}.
Haven't found an easier solution. Quite sad for a language that has been under active development for decades.
If you are Android developer you can use:
<pre class=”prettyprint”>
TODO:your code.
</pre>
To pretty print your code in Javadoc with Java code.
Try replacing "code" with "pre". The pre tag in HTML marks the text as preformatted and all linefeeds and spaces will appear exactly as you type them.
I work through these two ways without any problem:
<pre>
<code>
... java code, even including annotations
</code>
</pre>
and
<pre class="code">
... java code, even including annotations
</pre>
Of course the latter is more simplest and observe the class="code" part
I enclose my example code with <pre class="brush: java"></pre> tags and use SyntaxHighlighter for published javadocs. It doesn't hurt IDE and makes published code examples beautiful.
Using Java SE 1.6, it looks like all UPPERCASE PRE identifiers is the best way to do this in Javadoc:
/**
* <PRE>
* insert code as you would anywhere else
* </PRE>
*/
is the simplest way to do this.
An Example from a javadoc I got from a java.awt.Event method:
/**
* <PRE>
* int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
* int offmask = CTRL_DOWN_MASK;
* if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
* ...
* }
* </PRE>
*/
This produces output that looks exactly like the regular code, with the regular code spacings and new lines intact.
In Visual Studio Code at least, you can force a Javadoc comment to respect line-breaks by wrapping it in triple-backticks, as seen below:
/** ```markdown
* This content is rendered in (partial) markdown.
*
* For example, *italic* and **bold** text works, but [links](https://www.google.com) do not.
* Bonus: it keeps single line-breaks, as seen between this line and the previous.
``` */