This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am getting the following errors.
Exception in thread "main" java.lang.NullPointerException at ReadFile.createDogs(ReadFile.java:41) at ReadFile.main(ReadFile.java:55)
The file is opening to the desktop. I feel I am missing something very
simple. I have included the class file also. The error is specific to
dogOutput.println(dogInfo);
Thank you.
import java.io.*;
import java.io.PrintWriter;
public class ReadFile
{
private static Canine[] getCanine()
{
Canine[] canines= new Canine[5];
canines[0]=new Canine("Thoedore", "Male", "Medium", 7, 50);
canines[1]=new Canine("Magellan", "Male", "Medium", 5, 50);
canines[2]=new Canine("Duffy", "Male", "Small", 10, 10);
canines[3]=new Canine("Sammie", "Female", "Medium", 7, 65);
canines[4]=new Canine("Snowball", "Male", "Small", 13, 17);
return canines;
}
private static PrintWriter createFile(String fileName)
{
try{
File listOfDogs = new File(fileName);
PrintWriter infoToWrite= new PrintWriter
( new BufferedWriter
(new FileWriter(listOfDogs)));
}
catch (IOException e)
{
System.out.println(" An I/O Error Occurred.");
System.exit(0);
}
return null;
}
private static void createDogs(Canine dog, PrintWriter dogOutput)
{
String dogInfo= dog.name + " " + dog.gender+ " " + dog.size +" ";
dogInfo += Integer.toString(dog.age)+ " "+
Double.toString(dog.weight);
dogOutput.println(dogInfo);
}
public static void main (String[] args)
{
Canine[] canines= getCanine();
System.out.println("Here1");
PrintWriter dogOutput =
createFile("/Users/Teacher/Desktop/Dogs.text");
for(Canine dogs: canines)
{
createDogs(dogs, dogOutput);
System.out.println("Here5");
}
dogOutput.close();
}
private static class Canine extends Pet
{
public static final String type="Dog";
public Canine()
{
super.type=this.type;
}
public Canine(String name, String gender, String size, int age, double
weight)
{
super.type=this.type;
super.name=name;
super.gender=gender;
super.size=size;
super.age=age;
super.weight=weight;
}
public static void setType(String word)
{
}
}
private static class Pet
{
public static String type;
public static String color;
public static String gender;
public static String temperment;
public static String food;
public static int age;
public static double weight;
public static String name;
public static String size;
public Pet()
{
}
public Pet(String type,String color,String gender,String temperment,
String food,int age,double weight,String name,String size)
{
type=type;
color=color;
gender=gender;
temperment=temperment;
food=food;
age=age;
weight=weight;
name=name;
size=size;
}
public Pet(String name, String gender, String size, int age, double
weight)
{
name=name;
gender=gender;
size=size;
age=age;
weight=weight;
}
public static String getType()
{
return type;
}
public static String getName()
{
return name;
}
public static String getSize()
{
return size;
}
public static String getColor()
{
return color;
}
public static String getTemperment()
{
return temperment;
}
public static String getFood()
{
return food;
}
public static String getGender()
{
return gender;
}
public static int getAge()
{
return age;
}
public static void setType(String word)
{
type=word;
}
public static void getName(String word)
{
name=word;
}
public static void setSize(String word)
{
size=word;
}
public static void setColor(String word)
{
color=word;
}
public static void getTemperment(String word)
{
temperment=word;
}
public static void setFood(String word)
{
food=word;
}
public static void setGender(String word)
{
gender=word;
}
public static void setAge(int ageSet)
{
age=ageSet;
}
public static void setWeight(double weightSet)
{
weight=weightSet;
}
public static void setName(String NameSet)
{
name=NameSet;
}
public String toString()
{
return ("Type "+type+"\n" +" Name "+name+"\n"+" Age "+age+"\n"+
"Size "+ size+"\n"+" Gender "+gender+"\n"+" Weight "+weight);
}
}
}
Try renaming the dogOutput variable. In java, you can't pass variables between static methods with the same name.
The simple answer: In createFile() you always return null instead of the instance of PrintWriter you just created as infoToWrite.
The complete answer: You need to strengthen your knowledge of OOP. The unnecessary use of static members, for instance, can have undesired effects.
Related
I have a info class Vehicle that has multiple attributes and I have a Moped info class that extends the vehicle class. I need to create a main program that I can add multiple mopeds to an array list and then print them. Here is my attempt:
info class1:
package data;
public class Vehicle {
private float price;
private String color;
private int maximumSpeed;
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color= color;
}
public int getMaximumSpeed() {
return maximumSpeed;
}
public void setMaximumSpeed(int maximumSpeed) {
this.maximumSpeed = maximumSpeed;
}
public String toString() {
return "Price: "+this.price+" Color: "+this.color+" Maximum speed: "+this.maximumSpeed;
}
}
Info class2:
package data;
public class Moped extends Vehicle{
private String Brand;
private String type;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand= brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toString() {
return "Brand: "+this.brand+" Type: "+this.type;
}
}
Main program:
package app;
import java.util.ArrayList;
import java.util.Scanner;
import data.*;
public class ExtendsTest {
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
Moped mp=new Moped();
askForMopedInfo(mp);
lista.add(mp);
printMoped(list);
}
private static void printMoped(ArrayList<Moped> list) {
for (int i=0;i<list.size(); i++) {
System.out.println(list.get(i));
}
}
private static void askForMopedInfo(Moped mp) {
Scanner scanner = new Scanner(System.in);
System.out.print("Brand: ");
String k = scanner.nextLine();
mp.setBrad(k);
System.out.print("Type: ");
k = scanner.nextLine();
mp.setType(k);
System.out.print("Price: ");
int k1 = Integer.parseInt(scanner.nextLine());
mp.setPrice(k1);
System.out.print("Color: ");
k = scanner.nextLine();
mp.setColor(k);
System.out.print("Maximum speed: ");
k1 = Integer.parseInt(scanner.nextLine());
mp.setMaximumSpeed(k1);
}
}
When I run the program I get asked for:
Brand:
Type:
Price:
Color:
Maximum speed:
But the program only prints:
Brand: x Type: x
And I am still not sure how to add multiple mopeds to the array list. Any help would be much appreciated!
Update toString method of your Moped class, like this:
package data;
public class Moped extends Vehicle {
/*
other code
*/
public String toString() {
return super.toString() +" Brand: "+this.brand+" Type: "+this.type;
}
}
to Add more mopeds to the array list, you can do this:
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
While(true){
Moped mp=new Moped();
askForMopedInfo(mp);
list.add(mp);
printMoped(list);
}
}
I'm reading the book "Thinking in Java" by Bruce Eckel. I came across this assertion in the inner class chapter, which says: "the only justification for using a local inner class instead of an anonymous inner class is if you need a named constructor and/or an overloaded constructor"
I don't now if i understood well but:
Is this the way of overloading constructors of Inner(local classes) inside method?
abstract class ForInner {
abstract String getName();
abstract void setName(String newName);
abstract int getNumber();
abstract void setNumber(int newNumber);
}
class Outer{
public ForInner getSomeInner(String name) {
class LocalInner extends ForInner{
private String myName;
private int myNumber;
public LocalInner(String myName) {
this.myName = myName;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
}
return new LocalInner(name);
}
public ForInner getSomeInner(int number) {
class LocalInner extends ForInner{
private String myName;
private int myNumber;
public LocalInner(int myNumber) {
this.myNumber = myNumber;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
}
return new LocalInner(number);
}
}
I'm not sure if the assertion referring to this. But might have a guess that is not the case because How different it would be of using in this way
abstract class ForInner {
abstract String getName();
abstract void setName(String newName);
abstract int getNumber();
abstract void setNumber(int newNumber);
}
lass Outer{
public ForInner inner (String name) {
return new ForInner() {
private String myName;
private int myNumber;
{
myName = name;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
};
}
public ForInner inner (int number) {
return new ForInner() {
private String myName;
private int myNumber;
{
myNumber = number;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
};
}
}
thank in advance?
public class OuterClass {
Runnable printA = new Runnable() {
#Override
public void run() {
System.out.println("Print A");
}
};
Runnable printB = new Runnable() {
#Override
public void run() {
System.out.println("MESSAGE:" + " " + "Print B");
}
};
class PrintMessage implements Runnable {
private String msg;
public PrintMessage(String msg) {
this.msg = msg;
}
// overloaded constructor
public PrintMessage(String prefix, String msg) {
this.msg = prefix + " " + msg;
}
#Override
public void run() {
System.out.println(msg);
}
}
Runnable printC = new PrintMessage("Print C");
Runnable printD = new PrintMessage("Print D");
Runnable printE = new PrintMessage("MESSAGE:", "Print E");
public static void main(String[] args) {
OuterClass sample = new OuterClass();
sample.printA.run();
sample.printB.run();
sample.printC.run();
sample.printD.run();
sample.printE.run();
}
}
There are two instances of Runnable implemented as anonymous classes. While printA is created you cannot use it to create printB. You should create anonymous class from the beginning (i.e. override all abstract methods).
If an inner class created based on Runnable, you can use it in form new PrintMessage() to create new instances. Besides that it's possible to use non-default constructors.
Ah ok so when have this code
class OuterClass {
public Runnable printA() {
return new Runnable() {
#Override
public void run() {
System.out.println("Print A");
}
};
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
Runnable printA = outer.printA();
Runnable printB = outer.printA();
}
}
In this case I'm not creating multiply instances of a single anonymous inner class. Instead I'm creating multiple anonymous classes that use the same source code. Is that Rigth?!
Thanks
As I said in theme, but when I am trying to set a new object, the old ones looks same as the last one:
public class Test {
private static List<Booking> list = new ArrayList<Booking>();
private static List<Booking> lista = new ArrayList<Booking>();
public static void main(String[] args)
{
Booking[] book=new Booking[3];
book[0]=new Booking();
book[1]=new Booking();
book[2]=new Booking();
list.add(0,book[0]);
list.add(1,book[1]);
list.add(2,book[2]);
list.get(0).setYear("1900");
list.get(0).setMonth("january");
list.get(1).setMonth("september");
list.get(1).setYear("1600");
list.get(2).setYear("2000");
list.get(2).setMonth("may");
System.out.println(list.get(0).getBook());
System.out.println(list.get(1).getBook());
System.out.println(list.get(2).getBook());
}
}
And the booking class:
public class Booking
{
public static String getMark()
{
return m;
}
public static String getWym()
{
return w;
}
public static String getWyw()
{
return wyw;
}
public static String getImie()
{
return imie;
}
public static String getNaz()
{
return nazwis;
}
public static String getNr()
{
return nr;
}
public void setMark(String m)
{
this.m=m;
}
public void setWym(String w)
{
this.w=w;
}
public void setWyw(String wyw)
{
this.wyw=wyw;
}
public void setImie(String imie)
{
this.imie=imie;
}
public void setNaz(String nazwis)
{
this.nazwis=nazwis;
}
public void setNr(String nr)
{
this.nr=nr;
}
public void setYear(String year)
{
this.year=year;
}
public void setMonth(String month)
{
this.month=month;
}
public void setDay(String day)
{
this.day=day;
}
public void setHour(String hour)
{
this.hour=hour;
}
public static String getYear()
{
return year;
}
public static String getMonth()
{
return month;
}
public static String getDay()
{
return day;
}
public static String getHour()
{
return hour;
}
public String getBook()
{
String Book=getYear()+getMonth()+getDay()+getHour()+getMark()+getWym()+getWyw()+getImie()+getNaz()+getNr();
return Book;
}
private static String year;
private static String month;
private static String day;
private static String hour;
private static String m;
private static String w;
private static String wyw;
private static String imie;
private static String nazwis;
private static String nr;
}
Here is what I got after compilation:
2000maynullnullnullnullnullnullnullnull
2000maynullnullnullnullnullnullnullnull
2000maynullnullnullnullnullnullnullnull
Instead of:
1900januarynullnullnullnullnullnullnullnull
1600septembernullnullnullnullnullnullnullnull
2000maynullnullnullnullnullnullnullnull
remove the static from your all your fields in Booking
You are using static variables inside your Booking class and because of this all instances have common fields year, month, etc...
Making field static is like attaching it to whole class context not instance.
The effect is that the last modification (setting may 2000) is modifying all instances in result
You should make these fields non static and then instances will have their own values
class Booking {
private String year;
private String month;
private String day;
//another fields...
public String getYear() {
return this.year;
}
//another methods...
}
Also take a look at reference to understand usage of static keyword. You definitely abuse it.
I have just recently learned about setter , getters and this.(somthing).
I having quite a hard time undersatnding when to use getters and when to use setters .
Another thing , can i use setter method to print out ?
For Example :
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
newAge = workerAge;
}
public void setWorkerName(String newName) {
newName = workerName;
}
public int setIde(int ide) {
ide = workerIde;
return ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde());
}
}
the system out print shows an error and i didnt understand why , is it because only getters can be used in the sysout command ?
No offense intended, but your setters are all wrong. You should assign your properties to the values passed in the setter, not setting the value again. So your code should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
}
If you need getters, it should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
public int getIde() {
return workerIde;
}
}
Then you can print, e.g. System.out.println(worker1.getIde());
You should be using a getter method to get the values.
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName=newName;
}
public int getIde() {
return workerIde;
}
public void setIde(int ide) {
workerIde = ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.getIde());
}
}
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
this.workerAge = newAge;
}
public void setWorkerName(String newName) {
this.workerName = newName;
}
public int setIde(int ide) {
this.workerIde = ide;
return this.workerIde;
}
}
public class Car {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde(56));
}
}
This question already has answers here:
Missing method body, or declare abstract in Java
(4 answers)
Closed 7 years ago.
public class Hw7pr1
{
public static void main(String[] args);
String eName;
double payrate;
public Hw7pr1(String name, double rate)
{
eName = name;
payrate = rate;
}
public String getEName()
{
return eName;
}
public void setEName(String name)
{
eName = name;
}
public double getPayrate()
{
return payrate;
}
public void setPayrate(double payrate)
{
this.payrate = payrate;
}
}
This is the mistake I get when compiling it.
Hw7pr1.java:3: error: missing method body, or declare abstract
public void main(String[] args);
^
Take out the semicolon after your main method declaration
should be like this
public static void main(String[] args) {
...
}
Remove ";" at the end of your main method and add instead a bracket
public static void main(String[] args){
and at the end of your main method (which seems not really used - empty) a closing one
}
The class:
public class Hw7pr1 {
public static void main(String[] args) {
// do something
}
String eName;
double payrate;
public Hw7pr1(String name, double rate) {
eName = name;
payrate = rate;
}
public String getEName()
{
return eName;
}
public void setEName(String name)
{
eName = name;
}
public double getPayrate()
{
return payrate;
}
public void setPayrate(double payrate)
{
this.payrate = payrate;
}
}