This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm basically running this code:
AddressBook.java
/*
* 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 addressbook;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author hassan
*/
public class AddressBook extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MainWindow.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setResizable(false);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
new AddressBookMapper().parseDataFile();
}
}
AddressBookMapper.java:
/*
* 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 addressbook;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
*
* #author hassan
*/
public class AddressBookMapper {
private File dataFile;
private FileWriter fileWriter;
private PrintWriter printWriter;
public ArrayList lines;
private void openDataFile() {
this.dataFile = new File("src/addressbook/datafile.txt");
}
public void writeData() {
System.out.println(this.lines);
Iterator iterator = this.lines.iterator();
System.out.println(this.lines.get(0));
while(iterator.hasNext()) {
System.out.println();
System.out.println("-----");
}
}
public void createAddress(String fullName, String email, String telephoneNumber, String mobileNumber) {
this.openDataFile();
try {
this.fileWriter = new FileWriter(this.dataFile, true);
this.printWriter = new PrintWriter(this.fileWriter);
this.printWriter.append(fullName + "," + email + "," + telephoneNumber + "," + mobileNumber + "\n");
this.printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getLastId() {
return 0;
}
public void parseDataFile() {
File dataFile = new File("src/addressbook/datafile.txt");
try {
Scanner scanner = new Scanner(dataFile, "UTF-8").useDelimiter("\\n");
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
} catch (IOException e) {
e.printStackTrace();
}
this.writeData();
}
private int findLastAddressId() {
return 0;
}
}
My data file text:
ff,ff,fff,ff
krfr,frffr,frfs,ff
a,a,b,c
d,a,f,e
fa,e,f,a
But, for some reason, I get this output:
ff,ff,fff,ff
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
krfr,frffr,frfs,ff
a,a,b,c
d,a,f,e
fa,e,f,a
null
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.NullPointerException
at addressbook.AddressBookMapper.writeData(AddressBookMapper.java:36)
at addressbook.AddressBookMapper.parseDataFile(AddressBookMapper.java:69)
at addressbook.AddressBook.main(AddressBook.java:36)
... 11 more
Exception running application addressbook.AddressBook
Java Result: 1
Any solution? I am basically trying to get the text from my data file line by line and stack it up into my ArrayList. Also, when writing my datafile adds a blank line in the end of the document.
Can you please try -
while(scanner.hasNext()) {
lines.add(scanner.next());
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
im trying to read a csv with dummy data into java arraylists. I don't know what happened, but I get the described error message above the next day I started the program again.
Here's my Code. I hope you don't get irritated by the german variables. I think the structure is important.
package Aufgabe2;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import Aufgabe2.Models.Einlagekonto;
import Aufgabe2.Models.Girokonto;
import Aufgabe2.Models.Kunde;
public class Kundenreport {
public static void main(String[] args) throws ParseException, FileNotFoundException {
Scanner scanner = new Scanner(System.in);
List<Kunde> kunde = new ArrayList<Kunde>();
String pathKunden = "/Users/testuser/OneDrive/03_Privat/05_Code/01_Java/university/project8/src/Aufgabe2/Data/Kunden.csv";
String line = null;
try {
BufferedReader kundenReader = new BufferedReader(new FileReader(pathKunden));
kundenReader.readLine();
while ((line = kundenReader.readLine()) != null) {
String[] valuesKunden = line.split(";");
kunde.add(new Kunde(valuesKunden[0], valuesKunden[1], valuesKunden[2], valuesKunden[3]));
}
kundenReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is the "Kunde" (engl. Customer) Class which inherits from the abstract class "Konto"
package Aufgabe2.Models;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import Aufgabe2.Abstract.Konto;
public class Kunde extends Konto {
public Kunde() {
}
// Kunde ohne Konten
public Kunde(String kundenNr, String name, String vorname, String kundeSeit) {
super(kundenNr, name, vorname, kundeSeit);
}
And the "Konto" (engl. account) class possesses the attributes, abstract methods and getters/setter methods.
package Aufgabe2.Abstract;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
import Aufgabe2.Models.Kunde;
public abstract class Konto {
public final static Date today = new Date();
public Scanner scanner = new Scanner(System.in);
public static SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.GERMAN);
private String kundenNr, name, vorname, kundeSeit;
private double kontoStdGiro, kontoStdEinlage;
private String anlagedatum, faelligkeitsdatum;
public Konto() {
}
// Nur Kunde ohne Konten
public Konto(String kundenNr, String name, String vorname, String kundeSeit) {
this.kundenNr = kundenNr;
this.name = name;
this.vorname = vorname;
this.kundeSeit = kundeSeit;
}
I was searching for a while and thankful for every advise from you.
Thanks!
By the way, here is the folder structure of the project:
Screenshot of repository
Most languages - such as Java or Python are zero-indexed, meaning they start from 0 instead of 1 like we normally do when counting. So when accessing a particular index we have to go one less than its number, for example, if we want the second element in array arr, we would do arr[1]. So in this case an array of length one only has one index, meaning arr[0]. For further reading on zero index here's a link: https://softwareengineering.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm
I'm writing code for practicing setting up a server, but when I'm setting up the Input and Output streams, it says that I have to catch the IO Exception. However, I've already caught the exception. Here is the code:
/*
* 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 server;
import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.application.Platform;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
/**
*
*
*/
public class Server extends Application {
#Override
public void start(Stage primaryStage) {
TextArea ta = new TextArea();
Scene scene = new Scene(new ScrollPane(ta), 450, 200);
primaryStage.setTitle("Server");
primaryStage.setScene(scene);
primaryStage.show();
new Thread(() ->
{
try
{
ServerSocket serversocket = new ServerSocket(8000);
Platform.runLater(() -> {
ta.appendText("Server started at " + new Date() + '\n');
Socket socket = serversocket.accept();
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
while(true)
{
double radius = inputFromClient.readDouble();
double area = Math.PI* radius * radius;
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: " + radius
+ '\n');
ta.appendText("Area is: " + area + '\n');
});
}
});
}
catch(IOException ex)
{
ex.printStackTrace();
}
}).start();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
The first time I call a method that could throw an exception, when setting up the server socket, there is no error detected on the IDE. However, the next time, when I try and set up the socket, and all subsequent times when an exception could happen, the IDE says that I need to catch the exception, even though I thought since it was all in a try/catch block, it was already caught. Thanks for any help.
I have a problem with my code i'm working on an antologie file using Protege OWL API (3.4.8) and i want to have all the classes define by the user in the ontologie , the problem is i keep having errors in the for loop i can't fix those errors, is there any way to get the classes.
package Test;
import java.util.Collection;
import javax.swing.text.html.HTMLDocument.Iterator;
import antlr.collections.List;
import edu.stanford.smi.protege.model.Cls;
import edu.stanford.smi.protegex.owl.ProtegeOWL;
import edu.stanford.smi.protegex.owl.jena.JenaOWLModel;
import edu.stanford.smi.protegex.owl.model.OWLDatatypeProperty;
import edu.stanford.smi.protegex.owl.model.OWLIndividual;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import edu.stanford.smi.protegex.owl.model.OWLNamedClass;
import edu.stanford.smi.protegex.owl.model.OWLObjectProperty;
import edu.stanford.smi.protegex.owl.model.RDFSClass;
public class Class4 {
public static JenaOWLModel owlModel =null;
public static String scorKos_Uri="C:/Users/souad/Desktop/SCOR-KOS.owl";
//where my ontologie file exist
//change the URI by this
"http://protege.cim3.net/file/pub/ontologies/travel/travel.owl"; to have a
OWL file
/**
* #param args
*/
public static void main(String[] args) {
/**
* ontologie
*/
try {
owlModel=ProtegeOWL.createJenaOWLModelFromURI(scorKos_Uri);
System.out.println("Worked");
Collection classes = owlModel.getUserDefinedOWLNamedClasses();
for (Iterator it = classes.iterator(); it.hasNext();) {
OWLNamedClass cls = (OWLNamedClass) it.next();
Collection instances = cls.getInstances(false);
System.out.println("Class " + cls.getBrowserText() + " (" +
instances.size() + ")");
for (Iterator jt = instances.iterator(); jt.hasNext();) {
OWLIndividual individual = (OWLIndividual) jt.next();
System.out.println(" - " + individual.getBrowserText());
}
}
}catch (Exception exception) {
System.out.println("Error can't upload the ontologie ");
System.exit(1);
}
}
}
You're not importing java.util.Iterator.
I'm starting in java and have a problem with sockets, I wanted my server Meet and greet a value and then wanted to turn it into a String, to then include in a conditionif. However, despite the server approved the text without problem, I can not pass the value for a String.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javasockets;
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.System.exit;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Nuno
*/
public class JavaSockets {
public static String T = "s";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
try {
ServerSocket sckServer = new ServerSocket(5000);
System.out.println("Porta 5000 aberta!");
Socket sck;
while (true) {
sck = sckServer.accept();
try (Scanner entrada = new Scanner(sck.getInputStream())) {
while (entrada.hasNextLine()) {
System.out.println(entrada.nextLine());
}
String texto = entrada.nextLine();
System.out.println("ola" + texto);
String fnames = texto;
System.out.println("ola" + fnames);
System.out.println(texto);
if (texto.equals(T)) {
System.out.println("LOOL");
}
}
sckServer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Cliente code, send messages to the socket 127.0.0.1", 5000
package javasockets;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Nuno
*/
public class cliente {
public static void main(String[] args) throws IOException {
while (true) {
Socket cliente = new Socket("127.0.0.1", 5000);
System.out.println("O cliente se conectou ao servidor!");
Scanner teclado = new Scanner(System.in);
PrintStream saida = new PrintStream(cliente.getOutputStream());
while (teclado.hasNextLine()) {
saida.println(teclado.nextLine());
}
saida.flush();
saida.close();
teclado.close();
}
}
static Object getInetAddress() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
thanks for the help
Every call to nextLine () method, the server waits to receive a new string, but in the implementation of your client will only send a single string.
So try:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.System.exit;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Nuno
*/
public class JavaSockets {
public static String T = "s";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
try {
ServerSocket sckServer = new ServerSocket(5000);
System.out.println("Porta 5000 aberta!");
Socket sck;
while (true) {
sck = sckServer.accept();
try (Scanner entrada = new Scanner(sck.getInputStream())) {
while (entrada.hasNextLine()) {
String texto = entrada.nextLine();
System.out.println(texto);
System.out.println("ola" + texto);
String fnames = texto;
System.out.println("ola" + fnames);
System.out.println(texto);
if (texto.equals(T)) {
System.out.println("LOOL");
}
}
}
sckServer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
So im trying to make a program that you input a flash game URL and it downloads the .swf file. Shown here:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Main.java
*
*
*/
public class Main {
/**
* Reads a web page into a StringBuilder object
* and prints it out to console along with the
* size of the page.
*/
public void getWebSite() {
try {
URL url = new URL("http://www.vivalagames.com");
URLConnection urlc = url.openConnection();
BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
StringBuilder builder = new StringBuilder();
int byteRead;
while ((byteRead = buffer.read()) != -1)
builder.append((char) byteRead);
buffer.close();
Logger.log(builder.toString());
System.out.println("The size of the web page is " + builder.length() + " bytes.");
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Starts the program
*
* #param args the command line arguments
*/
public static void main(String[] args) {
new Main().getWebSite();
}
}
I have got to the part where it downloads the websites html and puts it into a file called output.txt. Now what im trying to do is make it search that text file till it finds the words ".swf", the searcher code is:
import java.io.*;
import java.util.Scanner;
import java.util.regex.MatchResult;
public class Sercher {
public static void main() throws FileNotFoundException {
Scanner s = new Scanner(new File("output.txt"));
while (null != s.findWithinHorizon("(?i)\\b.swf\\b", 0)) {
MatchResult mr = s.match();
System.out.printf("Word found: %s at index %d to %d.%n", mr.group(),
mr.start(), mr.end());
}
}
}
Now how do I make the main.java code run the function from the Searcher.java?
This should do it:
public static void main(String[] args) {
new Main().getWebSite();
Searcher.main();
}
Make an instance of the Searcher class in the Main class.
public static void main(String[] args) {
new Main().getWebSite();
Searcher search = new Searcher();
}
or simply, use Searcher.main();.
First of all, storing the downloaded HTML in a file to re-read this file right after is not a really good idea. You could do everything in memory.
Think in terms of objects and methods. You basically have two objects here: a Downloader and a Searcher. And you don't want two main methods to your program: only a single one. This main method should look like this:
// create the object which downloads the HTML
Downloader downloader = new Downloader();
// Ask it to download, and store the result into a String variable
String downloadedHtml = downloader.download();
// create the object which can search into a String for .swf references
Searcher searcher = new Searcher();
// pass it the String to search into
searcher.searchSwfIn(downloadedHtml);
You need to put your classes to packages and import Searcher package to your main class.
Example:
package foo.bar.package;
import for.bar.package2.Searcher;
/*
Other import declarations
*/
public class Main {
/*
Your code
*/
public static void main(String[] args) {
new Main().getWebSite();
new Searcher().search();
}
}
package for.bar.package2;
/*
Import declarations
*/
public class Searcher {
public void search() throws FileNotFoundException {
Scanner s = new Scanner(new File("output.txt"));
while (null != s.findWithinHorizon("(?i)\\bjava\\b", 0)) {
MatchResult mr = s.match();
System.out.printf("Word found: %s at index %d to %d.%n", mr.group(),
mr.start(), mr.end());
}
}
}