Eclipse will not compile - eclipse

So. I'm currently writing this code:
https://www.youtube.com/watch?v=pHxtKDENDdE&list=PLFE2CE09D83EE3E28&index=30
Here is the code. This is identical to that in the Youtube video:
import java.util.Random;
class ArrayElementsasCounters {
public static void main(String[] args) {
Random rand = new Random();
int freq[] = new int[7];
for(int roll=1;roll<1000;roll++) {
++freq[1+rand.nextInt(6)];
}
System.out.println("Face\tFrequency");
for(int face=1;face<freq.length;face++); {
System.out.println(face+"\t"+freq[face]);
}
}
}
I get this compile error:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: face cannot be resolved to a variable face cannot be
resolved to a variable
at ArrayElementsasCounters.main(ArrayElementsasCounters.java:22)
Line 22 is: System.out.println(face+"\t"+freq[face]);
This is working perfectly for the guy in the Youtube video, but not for me. Why?

Remove the semi colon after for statement..
for(int face=1;face<freq.length;face++);
Remove this semicolon in your code..

Related

Running tests with VS Code (without Maven) using the "Test Runner for Java" extension

I'm trying to make a minimal working example of JUnit5 using Visual Studio code without Maven. The reason is that I'm trying to make a quick demo for 1st year students, and I don't have the time to explain Maven (it will be the subject of a later course).
My VS Code workspace has this structure (I'm on Linux so forward slashes are normal) :
The settings.json file contains:
{
"java.project.referencedLibraries": [
"demojunit/junit-platform-console-standalone-1.8.1.jar"
]
}
The DemoJUnit.java contains:
package demojunit;
import java.util.Scanner;
public class DemoJUnit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int integer = -1;
do {
System.out.print("Enter an integer between 1 and 20 : ");
if (keyboard.hasNextInt())
integer = keyboard.nextInt();
keyboard.nextLine();
} while ((integer < 1) || (integer > 20));
keyboard.close();
long result = computeFactorial(integer);
System.out.println("The factorial " + integer + "! gives " + result);
}
public static long computeFactorial(int number) {
if (number < 1)
return -1;
if (number > 20)
return -2;
long factorial = 1;
for (int i = 2; i <= number; i++) {
factorial = factorial * i;
}
return factorial;
}
}
And the DemoJUnitTest.java contains:
package demojunit;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class DemoJUnitTest {
#Test
public static void computeFactorial_CleanTest() {
long expected_value = 120;
long real_value = DemoJUnit.computeFactorial(5);
Assertions.assertEquals(expected_value, real_value);
}
#Test public static void computeFactorial_DirtyTest() {
long expected_value = -1;
long real_value = DemoJUnit.computeFactorial(0);
Assertions.assertEquals(expected_value, real_value);
}
}
The settings.json seems to work since the imports and #Test are not marked as errors in VS Code.
As you can see in the folder image, I downloaded the latest JUnit5 jar file, and it works when running from the command line:
However, running from the command line is not convenient, so I installed the "Test Runner for Java" extension.
The problem is that when running tests, something fails and I don't have any error messages, nor any indication what went wrong. I changed the extensions' settings to be verbose but I still get no error messages in the Terminal, the Debug Console, nor anywhere else.
All I get is :
Any idea why the extension fails (and fails to give any indication on why it fails)?

How to import other person's package?

import CtCILibrary.*;
public class RotateMatrix {
public static boolean rotate (int [][]matrix) {
if ( matrix.length == 0 || matrix.length != matrix[0].length) {
return false;
}
int n = matrix.length;
for ( int layer = 0 ; layer < n / 2 ; layer++ ) {
int first = layer;
int last = n - 1 - first;
for ( int i = first ; i < last; i++ ) {
int offset = i - first;
int top = matrix[first][i];
//left-> top
matrix[first][i] = matrix [last-offset][first];
//bottom -> left
matrix[last-offset][first] = matrix [last][last-offset];
//right -> bottom
matrix[last][last-offset]= matrix[i][last];
//top->right
matrix[i][last]=top;
}
}
return true;
}
Hi there, I'm trying to import the CtCI library to solve the problem but there's an error message. And from her GitHub, that was how she imported this class. I know we can import the class from java built-in library. But I'm not sure how import works when trying to import from someone else. Could someone explain it to me?
If you are doing serious programming for a long term app, and by import you refer to libraries/dependencies, I highly recommend you using maven for it.
If you don't use maven yet, you can just add the .jar files from you IDE to your project path, but with maven is way better.
If you mean importing a .java file written by someone else, to use part of it in your code, just put the file at your project path, you probably need to adapt its libraries and imports, and once ready you can just use its methods ans stuff. Just make sure you have tipped at the top of your current file the import sentence of that file.

Reading files from GCS line by line to append line numbers to it using FileBasedReader

So, I was trying to read a file from GCS line-by-line to append line numbers at the end of the line and later make a PCollection out of it(Basically, the goal is to index a PCollection). Hence I've written this code but gives errors:
Below is the implementation classes of FileBasedSource and FileBasedReader:
private static class LineSource extends FileBasedSource<String> {
public LineSource(String fileOrPattern) {
super(fileOrPattern);
}
private static class LineReader extends FileBasedSource.FileBasedReader<String> {
public LineReader(LineSource source) {
super(source);
}
}
Code I wrote which uses these classes to read file line by line is:
try {
LineSource<String> f = new LineSource(fileName);
LineReader<String> b = new LineReader(f);
b.startReading(channel);
int index = 0;
while(b.readNextRecord()){
LOG.info("FileBasedSource: "+b.getCurrent());
c.output(b.getCurrent()+","+index);
index++;
}
b.close();
} catch (IOException e) {
e.printStackTrace();
}
But i get these errors:
java:[115,49] ')' expected
[ERROR] flatFileTest.java:[115,57] illegal start of expression
[ERROR] flatFileTest.java:[175,2] reached end of file while parsing
I guess startReading() method should be implemented again maybe.
I'm relatively new to Dataflow. Can you please help on this?

C# - System.ObectDisposedException in MemoryStream for Capacity, Length, and Position Properties

When executing the code to render PDF file from Html Stream, code seems to be executing fine, but PDF is not generated.
When debugging through the code, it seems that everything works just fine until I do not start looking into MemoryStream object properties and notice the following under MemoryStream object:
This is the code:
public partial class WriteNotes : System.Web.UI.Page
{
...
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
...
using (System.IO.MemoryStream printStream = new System.IO.MemoryStream())
using (System.IO.StreamWriter printStreamWriter = new System.IO.StreamWriter(printStream))
using (System.Web.UI.HtmlTextWriter printWriter = new System.Web.UI.HtmlTextWriter(printStreamWriter))
{
base.Render(printWriter);
printWriter.Flush();
using (System.IO.StreamReader myStreamReader = new System.IO.StreamReader(printStream))
{
myStreamReader.BaseStream.Position = 0;
Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromHtmlStream(myStreamReader.BaseStream, System.Text.Encoding.Default, HttpContext.Current.Request.Url.ToString().Replace(HttpContext.Current.Request.Url.PathAndQuery, "/"));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
pdfDocument.Save(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
...
}
Executing the following line of code produces the described exception for MemoryStream.
Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromHtmlStream(myStreamReader.BaseStream, System.Text.Encoding.Default, HttpContext.Current.Request.Url.ToString().Replace(HttpContext.Current.Request.Url.PathAndQuery, "/"));
The same kind of exception happens if I do not use Disposable Pattern.
The same code is in production and works fine.
What can be the reason?
Sure enough, found it. Read the documentation here:
PdfConverter.GetPdfDocumentObjectFromHtmlStream(htmlStream, streamEncoding)
In a nutshell it says to close the document object which you are not doing in your code above.
PdfDocument.Close()
States it here too, always call method close on the document object once you are done with it. Try this updated code.
Also add the library you are using next time if you happen to know it. Some answers can be found right in the documentation (not all the time of course).
public partial class WriteNotes : System.Web.UI.Page
{
...
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
...
using (System.IO.MemoryStream printStream = new System.IO.MemoryStream())
using (System.IO.StreamWriter printStreamWriter = new System.IO.StreamWriter(printStream))
using (System.Web.UI.HtmlTextWriter printWriter = new System.Web.UI.HtmlTextWriter(printStreamWriter))
{
base.Render(printWriter);
printWriter.Flush();
using (System.IO.StreamReader myStreamReader = new System.IO.StreamReader(printStream))
{
myStreamReader.BaseStream.Position = 0;
Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromHtmlStream(myStreamReader.BaseStream, System.Text.Encoding.Default, HttpContext.Current.Request.Url.ToString().Replace(HttpContext.Current.Request.Url.PathAndQuery, "/"));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
pdfDocument.Save(HttpContext.Current.Response.OutputStream);
pdfDocument.Close(); // add this line and see what happens
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
...
}

Diagnosing netlogo extension command error

When I try to execute the first-n-integers extension example:
show noise:first-n-integers 5
I receive an error "ERROR: Expected command. " in the console or in the code tab.
I have mostly copied and pasted the class examples as is, just renaming them and putting them in a different package. I wish the error was a little more descriptive, as I suspect I am making a simple error somewhere.
I'm using 5.0.4 without the JRE and a 1.7.0_45 JRE/JDK on a x64 Windows 7 machine.
My manifest.txt file with fully-qualified class-manager and crlf at the end of the version line--
Manifest-Version: 1.0
Extension-Name: noise
Class-Manager: org.xyz.extensions.NoiseExtension
NetLogo-Extension-API-Version: 5.0 <--there is a crlf here
the jar is in a subfolder with my model file
test/
test.nlogo
noise/
noise.jar
This is my Class-Manager:
package org.xyz.extensions;
import org.nlogo.api.*;
public class NoiseExtension extends DefaultClassManager {
public void load(PrimitiveManager primitiveManager) {
primitiveManager.addPrimitive(
"first-n-integers", new org.xyz.extensions.NoiseGenerator());
}
}
This is the NoiseGenerator file:
package org.xyz.extensions;
import org.nlogo.api.*;
public class NoiseGenerator extends DefaultReporter {
public Syntax getSyntax() {
return Syntax.reporterSyntax(
new int[] {Syntax.NumberType()}, Syntax.ListType());
}
public Object report(Argument args[], Context context) throws ExtensionException {
// create a NetLogo list for the result
LogoListBuilder list = new LogoListBuilder();
int n ;
// use typesafe helper method from
// org.nlogo.api.Argument to access argument
try {
n = args[0].getIntValue();
}
catch(LogoException e) {
throw new ExtensionException( e.getMessage() ) ;
}
if (n < 0) {
// signals a NetLogo runtime error to the modeler
throw new ExtensionException
("input must be positive");
}
// populate the list. note that we use Double objects; NetLogo
// numbers are always Doubles
for (int i = 0; i < n; i++) {
list.add(Double.valueOf(i));
}
return list.toLogoList();
}
}
Thanks for any help.
AJB
This was asked and answered here:
https://groups.google.com/d/msg/netlogo-devel/eIq8drflsc8/7y_Ooh6R0sgJ
The answer was to correct the spelling of getSynax to getSyntax.