import java.lang.*;
import java.util.*;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.IOException;
public class Test
{
public static void main(String[] args) throws IOException
{
Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
boolean[] correctAnswers = new boolean[20];
infile.close();
}
}
I'm getting these errors for some reason:
C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol : class Scanner
location: class Test
Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
^
C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol : class Scanner
location: class Test
Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
^
2 errors
Tool completed with exit code 1
I have no idea what's going on.
Help is appreciated, Thanks.
Which version of Java are you using? Scanner was added in 1.5.
Run the following command on command prompt (terminal);
java -version
If the returned version number is less than 1.5 then you have to download the new version of Java. Scanner class is not available in prior versions. Download the new version of SDK from here;
Java SE Downloads
After setting up the new version of Java, add the following import statement in your source file;
import java.util.Scanner;
Now compile your source. It should go like a F16 now. But feel free to ask in case of any problem.
Related
i want read text file in java8, i am getting error "Type mismatch: cannot convert from FileReader to Reader". If I change Reader class to FileReader than I get error "The constructor BufferedReader(FileReader) is undefined"
My statements are
Reader fr = new FileReader("testfile.txt");
BufferedReader br = new BufferedReader(fr);
Please suggest
To confirm that you are having a class with the name FileReader, just use the full class name in the code :
java.io.Reader fr = new java.io.FileReader("testfile.txt");
java.io.BufferedReader br = new java.io.BufferedReader(fr);
This will assure that you use the specific class and not a yourPackage.FileReader class.
Then, since only FileReader seems to be problematic, you can clean it a bit like :
import java.io.*
...
Reader fr = new java.io.FileReader("testfile.txt");
BufferedReader br = new BufferedReader(fr);
Only specifying the FileReader full name.
NOTE:
using Class.GetPackage, you should find out which class you are using.
System.out.println(FileReader.class.getPackage());
Explanation:
JLS - 7.5. Import Declarations
The scope and shadowing of a type or member imported by these declarations is specified in §6.3 and §6.4.
6.4.1. Shadowing
A package declaration never shadows any other declaration.
A single-type-import declaration d in a compilation unit c of package p that imports a type named n shadows, throughout c, the declarations of:
any top level type named n declared in another compilation unit of p
any type named n imported by a type-import-on-demand declaration in c
any type named n imported by a static-import-on-demand declaration in c
Example
A
A.Run
A.Test
B
B.Test
In A.Run.java
System.out.println(Test.class.getPackage());
Here is the output :
Without import : Package A
Without import import B.* : Package A
Without import import B.Test : Package B
You're probably importing something other than java.io.BufferedReader and java.io.Reader.
This works
package com.company;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
Reader fr = new FileReader("testfile.txt");
BufferedReader br = new BufferedReader(fr);
}
}
Please check your imports;
I have a model obtained from weka classifier and I want to test it in java code, But when I read instances, an error appear:
Exception in thread "main" java.io.IOException: keyword #relation expected, read Token[Word], line 1
at weka.core.Instances.errms(Instances.java:1863)
at weka.core.Instances.readHeader(Instances.java:1740)
at weka.core.Instances.<init>(Instances.java:119)
at licenta1.LoadModelWeka.main(LoadModelWeka.java:18)
My code is:
package licenta1;
import weka.core.Instances;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.trees.J48;
import weka.classifiers.Evaluation;
import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader ;
public class LoadModelWeka
{
public static void main(String[] args) throws Exception {
// training
BufferedReader reader = null;
reader=new BufferedReader(new FileReader("D:\\aaaaaaaaaaaaaaaaaaaaaa\\Licenta\\BioArtLicTrainSetTask1.csv"));
Instances train =new Instances (reader);
train.setClassIndex(0);
reader.close();
NaiveBayes nb = new NaiveBayes();
nb.buildClassifier(train);
Evaluation eval = new Evaluation(train);
eval.crossValidateModel(nb, train, 10 , new Random(1));
System.out.println(eval.toSummaryString("\n Results \n=====\n",true));
System.out.println(eval.fMeasure(1)+" "+eval.precision(1)+" "+eval.recall(1)+" ");
}
}
Can somebody help me?
Mt training set is in .csv format
This snippet is useful to directly load csv content and convert them to Instances. Usually .arff is used for weka operations and this loader directly converts csv files to arff internally and then to Instances class.
CSVLoader loader = new CSVLoader();
loader.setSource(new File("filename.csv"));
Instances trainingDataSet = loader.getDataSet();
Instead of using Buffered Reader you can try
DataSource source = new DataSource("/some/where/data.arff");
For more information visit this link http://weka.wikispaces.com/Use+WEKA+in+your+Java+code
im using weka jar 3.7.10, and this is how i can load csv using weka :
DataSource source1 = new DataSource("D:\\aaaaaaaaaaaaaaaaaaaaaa\\Licenta\\BioArtLicTrainSetTask1.csv");
Instances pred_test = source1.getDataSet();
I have a ANTLR project called "Test.g4" and with antlrworks2 I created without any problems the files: Test.tokens, TestBaseListner.java, TestLexer.java, TestLexer.tokens, TestListener.java and TestParser.java.
Now I want to use the grammer in my program Test.java:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class Test {
public static void main(String[] args) throws Exception {
// create a CharStream that reads from standard input
ANTLRInputStream input = new ANTLRInputStream(System.in);
// create a lexer that feeds off of input CharStream
TestLexer lexer = new TestLexer(input);
// create a buffer of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// create a parser that feeds off the tokens buffer
TestParser parser = new TestParser(tokens);
ParseTree tree = parser.init(); // begin parsing at init rule
System.out.println(tree.toStringTree(parser)); // print LISP-style tree
}
}
When I try to compile it with "javac -classpath /path/java2/antlr-4.4-complete.jar Test.java" I get this errors:
Test.java:19: error: cannot find symbol
TestLexer lexer = new TestLexer(input);
^
symbol: class TestLexer
location: class Test
Test.java:19: error: cannot find symbol
TestLexer lexer = new TestLexer(input);
^
symbol: class TestLexer
location: class Test
Test.java:25: error: cannot find symbol
TestParser parser = new TestParser(tokens);
^
symbol: class TestParser
location: class Test
Test.java:25: error: cannot find symbol
TestParser parser = new TestParser(tokens);
^
symbol: class TestParser
location: class Test
4 errors
Thank you!
TestLexer.java and TestParser.java should also be compiled with Test.java in the same command, otherwise the compiler will not know where to look for their binaries. Try calling javac as follows:
javac -classpath /path/java2/antlr-4.4-complete.jar *java
Or manually pass all files:
javac -classpath /path/java2/antlr-4.4-complete.jar Test.java TestLexer.java TestParser.java
You need to build and import lexer and parser generated by ANTLR. To do it you need to:
add import statement to a file with your main method
put classes generated by ANTLR into a package as in your import statement
build both generated classes and class with your main method
The following java code:
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class extract
{
public static void main (String[] args) throws java.lang.Exception
{
String testData = new Scanner( new File("109.txt") ).useDelimiter("\\A").next();
//String testData = "#1|77|1391436891|1|1|00:1e:58:f4:15:f7|Nexus 4, 4.4, MAKOZ30d $1|1391436893 ?[176.08179, -13.839829, -1.0054213] %PKKV7|00:7f:28:3f:17:9d|-67|2437 %DC2VJ|f8:e4:fb:a0:06:f8|-71|2412 %VVWSP|00:7f:28:d5:92:65|-71|2462 %SVT8H|f8:e4:fb:8e:d6:9b|-77|2437 %ThreeBestFriends|20:10:7a:14:6a:f7|-66|2452 %2X4C8|00:7f:28:44:23:da|-75|2437 %STDGD|f8:e4:fb:70:86:f4|-82|2462 %DeathStar|00:7f:28:be:c8:94|-84|2412 %Freeinternet|00:1e:58:f4:15:f7|-59|2437 %QB657|00:26:62:b7:16:4b|-88|2462 %375F2|00:26:b8:3e:0a:14|-70|2412 %E1K38|00:26:62:cf:90:37|-81|2412";
String regularExpression = "\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}\\W{1}-\\d{2}";
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(testData);
while(matcher.find()) {
System.out.println(matcher.group(0));
}
}
}
generates the following output:
00:1a:1e:87:04:42|-87
00:1a:1e:8e:e9:a2|-77
00:1a:1e:87:04:51|-95
00:1a:1e:84:92:02|-84
00:1a:1e:8d:f7:a2|-67
00:1a:1e:82:b8:e1|-56
00:1a:1e:82:b8:e2|-54
00:1a:1e:82:b8:e0|-56
00:1a:1e:87:04:41|-88
00:1a:1e:8d:f7:b1|-78
00:1a:1e:8d:f7:b2|-78
I'm trying to save output file as an excel file separated by columns.
Does anybody has any suggestions on how to achieve this?
Thank you!
Just add some commas (currently you don't have any), and save it as a text file named some_file_name.csv. You may use e.g. a BufferedWriter for this.
Saying 'Excel file separated by commas' is incorrect, actually the proper term is 'comma separated values file' or 'CSV file'. Programs other than Excel can open such files too.
I'd like to write a Java app which can create executable jars at runtime. The "hello world" of what I want to do is write a Java app X that when run, generates an executable jar Y that when run, prints hello world (or perhaps another string not known until after Y is run).
How can I accomplish this?
The other answers require starting a new process, this is a method that doesn't. Here are 3 class definitions which produce the hello world scenario described in the question.
When you run XMain.main, it generates /tmp/y.jar. Then, when you run this at the command line:
java -jar /tmp/y.jar cool
It prints:
Hello darling Y!
cool
example/YMain.java
package example;
import java.io.IOException;
import java.io.InputStream;
public class YMain {
public static void main(String[] args) throws IOException {
// Fetch and print message from X
InputStream fromx = YMain.class.getClassLoader().getResourceAsStream("fromx.txt");
System.out.println(new String(Util.toByteArray(fromx)));
// Print first command line argument
System.out.println(args[0]);
}
}
example/XMain.java
package example;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
public class XMain {
public static void main(String[] args) throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, YMain.class.getName());
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream("/tmp/y.jar"), manifest);
// Add the main class
addClass(YMain.class, jarOutputStream);
// Add the Util class; Y uses it to read our secret message
addClass(Util.class, jarOutputStream);
// Add a secret message
jarOutputStream.putNextEntry(new JarEntry("fromx.txt"));
jarOutputStream.write("Hello darling Y!".getBytes());
jarOutputStream.closeEntry();
jarOutputStream.close();
}
private static void addClass(Class c, JarOutputStream jarOutputStream) throws IOException
{
String path = c.getName().replace('.', '/') + ".class";
jarOutputStream.putNextEntry(new JarEntry(path));
jarOutputStream.write(Util.toByteArray(c.getClassLoader().getResourceAsStream(path)));
jarOutputStream.closeEntry();
}
}
example/Util.java
package example;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Util {
public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[0x1000];
while (true) {
int r = in.read(buf);
if (r == -1) {
break;
}
out.write(buf, 0, r);
}
return out.toByteArray();
}
}
Do you have to write it in plain old Java? I'd use Gradle (a Groovy based build tool). You can have a custom task to write out the source files for Y (Groovy makes it really easy to write out templated files). Gradle makes it easy to generate an executable jar.
If you really want to roll your own from scratch, you'd need to use ZipOutStream to zip up the compiled files after calling javac via the Process API to compile the source.
Maybe a bit more info about why you want to do this would help get better answers
cheers
Lee
To elaborate on Lee's reply, you need to compile the source first. You can use Process or you can use the code from tools.jar directly as explained here. Then write out a MANIFEST.MF file and put it all together using ZipOutputStream as mentioned.
Step 1: figure out how to do it manually using the command line.
Step 2: automate this by calling the program from within Java.
http://devdaily.com/java/edu/pj/pj010016/
For step 1 I would suggest using ant - IDEs are not always automatable. So, either write out all the files from Java, or have some of the ant configurations included as resources n the project.