I don't know what's wrong with my main class. I dont know how to change it to fix it. Computer says: load from file cannot be referenced from static context. If I try to change it, my main class is missing.
public class Bsp3_1225814_3 {
public void static main(String [] args){
List<Linienzug> lst = new ArrayList<>();
load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_in");
dump_to_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_out");
}
public void load_from_file(String file) {
Scanner s = null;
try {
s = new Scanner(
new BufferedReader(new FileReader(file))).useDelimiter("\\n");
while (s.hasNext()) {
String[] in = s.next().split(":");
Linienzug l = new Linienzug();
for (int i=0; i<(in.length-1); i++){
l.add(new Punkt(Integer.parseInt(in[i]),
Integer.parseInt(in[i+1])));
}
this.lst.add(l);
}
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} finally {
if (s != null) {
s.close();
}
}
}
You cannot call a method that does not have the static keyword when you are in a static method. This is because there is an implicit reference to the this pointer which does not exist in a static context.
You cannot invoke instance methods, from a static context in this way.
You have to create an instance to invoke them.
Fix...
Bsp3_1225814_3 bsp3 = new Bsp3_1225814_3();
bsp3.load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_in");
bsp3.dump_to_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen Programmieren\\Projekte_Schurz\\1225814_3\\3_out");
public void static main(String [] args){
Bsp3_1225814_3 myObj = new Bsp3_1225814_3();
myObj.load_from_file("C:\\Users\\schurzm\\Google Drive\\TU\\2.Semester\\VU_Grundlagen
...
}
And declare lst as a member of your class.
Related
I am writing a calculator that loads all the classes needed through maven dependencies dynamically.such as slf4j,...
but i have a problem.since i don't want to set my class path to manifest,my customClassLoader does it itself.
but my logger is a private static final field and JVM want to load it before i call my customClassLoader and i get error!what can i do?
public class Calculator{
private List<String> expressions = new ArrayList<String>() ;
private List<String> results = new ArrayList<String>();
private final Logger logger = LoggerFactory.getLogger(Calculator.class);
public Calculator(){
//System.out.println("HELLO");
OperatorsCatalog catalog = new OperatorsCatalog();
}
public void calculate(String inputaddress){
//this.loadAddedClasses();
try{
logger.debug("Start to read the input file");
this.read(inputaddress);
logger.info("Input file is read");
for(int i = 0;i<expressions.size();i++){
ExpressionCalculator e = new ExpressionCalculator(expressions.get(i),OperatorsCatalog.getKnownOperators());
e.evaluate();
results.add(e.getResult());
}
logger.info("All evaluations ended");
logger.debug("Writing to file started");
this.write();
}
catch(FileNotFoundException e){
logger.warn("Can not find Input file",e);
}
catch(IOException er){
logger.warn(er.getMessage());
}
}
public void read(String inputaddress)throws FileNotFoundException,IOException{
CustomReader reader = new CustomReader();
expressions =reader.read(inputaddress);
}
public void write(){
CustomWriter writer = new CustomWriter();
writer.write(results);
}
/*public void loadAddedClasses(){
CustomClassLoader classloader = new CustomClassLoader();
classloader.loadClasses();
}*/
public static void main(String args[]) {
System.out.println("HELLO");
CustomClassLoader classloader = new CustomClassLoader();
classloader.loadClasses();
Calculator calculator = new Calculator();
calculator.calculate(args[0]);
}
}
For the assignment, I created text files
and defined main class for the test
public static void main(String[] args)
{
File input1 = new File("inputFile1.txt");
File input2 = new File("inputFile2.txt");
CalcCheck file1 = new CalcCheck(input1);
CalcCheck file2 = new CalcCheck(input2);
file1.CheckStart();
}
After I defined main class,
I defined other class
private File checkingFile;
CalcCheck (File files)
{
checkingFile = files;
}
void CheckStart()
{
Scanner sc = new Scanner (checkingFile);
System.out.println("checking start");
checkFileNull();
} ...
However, the Scanner sc = new Scanner (checkingFile) throws
FileNotFoundException
.
Can someone tell me what is the problem?
The constructor of Scan throws FileNotFoundException. This is actually a checked exception and you need to either surround the code with try ... catch ...
For example:
void CheckStart()
{
Scanner sc;
try {
sc = new Scanner (checkingFile);
} catch (FileNotFoundException e){
e.printStackTrace();
}
System.out.println("checking start");
checkFileNull();
}
Or you need to declare the exception in the method that calls the constructor.
For example:
void CheckStart() throws FileNotFoundException
{
Scanner sc = new Scanner (checkingFile);
System.out.println("checking start");
checkFileNull();
}
See this post for more information.
I'm making a Java program that needs to read info from a text file and then store it in an array and pass it to another class when called. My issue is that I can't seem to call it due to the IOException needed in the file reader class.
This is the main class that is supposed to call the fileReader.
public class window {
public static void main(String[] args){
String[] people = readFromText.read("people.txt");
}
}
File Reader Class
public class readFromText{
public static String[] read(String textFile) throws IOException {
BufferedReader inputFile = new BufferedReader(new
FileReader(textFile));
String[] array = new String[10];
String line = inputFile.readLine().toString();
int cnt = 0;
while (line!=null){
array[cnt] = line;
line = inputFile.readLine().toString();
cnt++;
}
inputFile.close();
return array;
}
}
Is it possible to do this, this way?
Firstly your code is not correct. You can not return the String[] array for the function need String[][].
Secondly for problem about exception you just need to catch it in your main class.
try {
String[] people = readFromText.read("people.txt");
} catch (IOException e) {
e.printStackTrace();
}
I am receiving a compile time error with the following code. The first code block scans in a text file and provides a get method for retrieving the largest value in the Array List. That block of code compiles fine. The second block of code is where I'm having difficulty. I'm fairly new to programming and am having difficulty understanding where I've made my error.
public class DataAnalyzer {
public DataAnalyzer(File data) throws FileNotFoundException
{
{
List<Integer> rawFileData = new ArrayList<>();
FileReader file = new FileReader("info.txt");
try (Scanner in = new Scanner(file)) {
while(in.hasNext())
{
rawFileData.add(in.nextInt());
}
}
}
}
public int getLargest(List<Integer> rawFileData){
return Collections.max(rawFileData);
}
}
This is the Tester Class I am attempting to implement. I am receiving a compile time error.
public class DataAnalyzerTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter your fileName: ");
}
public void printLargest(DataAnalyzer rawFileData)
{
rawFileData.getLargest();
System.out.println(rawFileData.getLargest());
}
}
I tryed to run your code, you have problem in the line 14 of the DataAnalyzerTester, you need to pass a parameter of List<Integer> to the method getLargest().
Try your Tester this way:
public class DataAnalyzerTester {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter your fileName: ");
}
public void printLargest(DataAnalyzer rawFileData) {
List<Integer> example = new ArrayList<Integer>();
example.add(0);
example.add(1);
example.add(2);
int result = rawFileData.getLargest(example);
System.out.println(result);
}
}
-------------- EDIT --------------------
Try something like this:
public class DataAnalyzer {
private List<Integer> rawFileData;
public DataAnalyzer(String fileName) throws FileNotFoundException {
rawFileData = new ArrayList<>();
FileReader file = new FileReader(fileName);
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
rawFileData.add(in.nextInt());
}
}
}
public int getLargest() {
return Collections.max(rawFileData);
}
}
public class DataAnalyzerTester {
public static void main(String[] args) throws FileNotFoundException {
DataAnalyzer analizer = new DataAnalyzer("info.txt");
System.out.println(analizer.getLargest());
}
}
I'm trying tackle this problem for a few days now but with no success.
Here is the code:
import java.util.*;
import java.io.*;
public class Portefeuille {
private ArrayList<Woning> woningen;
public Portefeuille(){
woningen = new ArrayList<Woning>();
}
public void voegToe(Woning w){
if(woningen.contains(w)==false)
woningen.add(w);
else
System.out.println(w.toString()+" komt al voor en is daarom niet toegevoegd.");
}
public ArrayList<Woning> woningenTot(int maxprijs){
ArrayList<Woning> totaal = new ArrayList<Woning>();
for(int i=0; i<woningen.size(); i++){
if((woningen.get(i)).KostHooguit(maxprijs))
totaal.add(woningen.get(i));
}
return totaal;
}
public static Portefeuille read(String infile){
Portefeuille woningen = new Portefeuille();
try
{
FileReader file = new FileReader(infile);
Scanner sc = new Scanner(file);
int aantalwoningen = sc.nextInt();
for(int i=0; i<aantalwoningen; i++){
Woning woning = Woning.read(sc);
woningen.voegToe(woning);
}
System.out.println(woningen.toString());
sc.close();
} catch(Exception e){
System.out.println(e);
}
return null;
}
}
And here is the main file
import java.util.*;
public class Test2 {
public static void main(String[] args){
Portefeuille bestand = Portefeuille.read("in.txt");
ArrayList<Woning> WTot = bestand.woningenTot(21500);
}
}
The error i am getting:
Exception in thread "main" java.lang.NullPointerException
at Test2.main(Test2.java:6)
I would really appreciate if someone could just at least point me in the right direction.
Thanks,
Jaspreet
You'll get a NullPointerException when you end up trying to call a method on a reference that points to null, rather than an object. In your case, that would be bestand.woningenTot(21500); because the call to Portefeuille.read("in.txt"); always returns null.
Your Portefeuille.read("in.txt") returns null instead of woningen.
public static Portefeuille read(String infile){
Portefeuille woningen = new Portefeuille();
try
{
FileReader file = new FileReader(infile);
Scanner sc = new Scanner(file);
int aantalwoningen = sc.nextInt();
for(int i=0; i<aantalwoningen; i++){
Woning woning = Woning.read(sc);
woningen.voegToe(woning);
}
System.out.println(woningen.toString());
sc.close();
} catch(Exception e){
System.out.println(e);
}
return woningen ;
}
}
you return null in your static read function... So you cant acces the object in line6.
Try to return woningen instead.
The method Portefeuille.read always returns null. You need to return the Portefeuille you are creating.
Side comments:
- Call close always in a finally section
- Use enhanced looks instead of normal for loops. Like for(String s: collectionOfStrings)
- Try to program using interfaces instead of concrete classes if possible. E.g.: use List instead of ArrayList
Well it looks to me like
public static Portefeuille read(String infile)
is always returning null. Perhaps there should be a
return woningen;
after sc.close();