implementing a method from one class to another? - java

I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically:
str= str + seats[i][j].toString();
I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong?
Airplane class:
public class Airplane
{
private Seat [ ] [ ] seats;
public static final int FIRST_CLASS = 1;
public static final int ECONOMY = 2;
private static final int FC_ROWS = 5;
private static final int FC_COLS = 4;
private static final int ECONOMY_ROWS = 5;
private static final int ECONOMY_COLS = 6;
public Airplane()
{
seats = new Seat[FC_ROWS][ECONOMY_COLS];
}
public String toString()
{
String str = "";
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
str= str + seats[i][j].toString();
}
str = str + "\n";
}
return str;
}
}
Seat Class:
public class Seat
{
private int seatType;
private boolean isReserved;
public static final int WINDOW = 1;
public static final int AISLE = 2;
public static final int CENTER = 3;
public Seat(int inSeatType)
{
seatType = inSeatType;
isReserved = false;
}
public int getSeatType()
{
return seatType;
}
public void reserveSeat()
{
isReserved = true;
}
public boolean isAvailable()
{
if (!isReserved)
{
return true;
}
else return false;
}
public String toString()
{
if(isReserved == false)
{
return "*";
}
else return "";
}
}

In Seat.toString you should print a " " not "".
You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS.
You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array.
When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.

seats seems to does not have Seat's instance.
Add this code :
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
seats[i][j] = new Seat();
}
}
below this :
seats = new Seat[FC_ROWS][ECONOMY_COLS];

I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.

Related

Java 2-D array returning NULL

I am working to create a "basic" UI connect4 game. I am having trouble figuring out why when I call to print the "board", I am getting null, in return. Have I not initialize the array? If so, how do I do so? ~Thanks
My constructor...
public class Connect4{
private String game[][];
public Conncet4(String game[][]){
this.game = game;
}
with one of my methods...
public void dropChipX(int colm){
for(int i = 0; i<game.length;i++) {
for(int j = 0; j<game[0].length;j++) {
if( j%2 == 0 )
game[game.length-1][col] = "|";
else
game[i][j] = " ";
}
}
if(game[game.length-1][colm] == " ")
game[game.length-1][colm] = "X";
else
game[(game.length-1)-count][col] = "X";
count++;
}
I also have a toString to print out the array
public String toString() {
String result = "";
for(int i = 0; i<game.length;i++) {
for(int j = 0; j<game[0].length;j++)
result = (game[i][j]);
result += "\n";
}
return result;
}
The thing I am having trouble with is that when I do run my main, its returning null
public class Connect4TextConsole {
public static void main(String[] args) {
String fun[][] = new String[6][15];
Connect4 connect = new Connect4(fun);
connect.dropChipX(3);
System.out.print(connect);
connect.dropChipY(2);
System.out.print(connect);
}
}
I would advise you to reconsider this code:
public class Connect4{
private String game[][];
public Conncet4(String game[][]){
this.game = game;
}
}
You should make a defensive copy of that 2D array inside the constructor.
Any code that gave you the reference to the game 2D array that's passed to the constructor can modify that mutable reference. Your private designation means nothing.

Hangman game errors

Here is my program so far:
import java.util.Arrays;
public class HangmanWord {
private String[] possibleWords = {"laptop", "college", "programing"};
private String word;
private char[] progress;
private int wrongCount = 0;
public HangmanWord() {
int randomPossibleWord = (int) (Math.random() * possibleWords.length-1);
String word = possibleWords[randomPossibleWord];
char[] progress = new char[word.length()];
Arrays.fill(progress,'-');
}
public void display() {
System.out.print(progress);
System.out.println();
}
public boolean guess(char c) {
boolean matchFound = false;
for (int i = 0; i < word.length(); i++ ) {
if (word.charAt(i) == c ) {
progress[i] = c;
matchFound = true;
}
}
return false;
}
public boolean isSolved() {
for (int i = 0; i < progress.length; i++ ) {
if(progress[i] == '-'){
return false;
}
}
return true;
}
public int getWrongCount() {
return wrongCount;
}
public String getWord() {
return word;
}
}
public class Hangman {
public static void main(String[] args) {
int MAX_INCORRECT = 5;
System.out.println("Welcome to Hangman.");
HangmanWord wordObj = new HangmanWord();
System.out.print("Here is your word: ");
wordObj.display();
}
}
My output should look something like this:
Welcome to Hangman.
Here is your word: ------
However, I am getting the following errors:
Welcome to Hangman.
Here is your word: Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Writer.java:127)
at java.io.PrintStream.write(PrintStream.java:503)
at java.io.PrintStream.print(PrintStream.java:653)
at HangmanWord.display(HangmanWord.java:16)
at Hangman.main(Hangman.java:9)
You are redefining the variable word and progress in your constructor. You should simply use them without declaring them as a new variables because they're already defined. Currently you are defining them locally, the constructor works but uses those local defined variables and not your object's word and progress variables, therefore when you leave scope and call display() it will use your object's progress array which was never actually initialized.
Change it to the following so you aren't redefining the variables word and progress like so
public HangmanWord() {
int randomPossibleWord = (int) (Math.random() * possibleWords.length-1);
word = possibleWords[randomPossibleWord];
progress = new char[word.length()];
Arrays.fill(progress,'-');
}

Java counter not counting properly

Hi I'm very new to Java and have this HW problem, we are asked to build Class LTile, a tile in the game of Scrabble.
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
My ID output didn't not print from 1 to 26, instead, they are all assign 26.
I suspect my ID attribute must be wrong, but couldn't figure out the exactly error. Any help is greatly appreciated! Thanks!
package hw2;
public class LTile {
char letter;
private int value;
private static int ID=0;
public LTile(){
this.letter = '?';
this.value = 0;
LTile.ID++;
}
public LTile(char letter, int value){
this.letter=letter;
this.value=value;
LTile.ID++;
}
public char getLetter(){
return this.letter;
}
public int getValue(){
return this.value;
}
public int getID(){
return LTile.ID;
}
public boolean equals(Object obj){
if(this ==obj){
return true;}
else{
return false;
}
}
public String toString(){
return "["+ID+":" + letter+","+value+"]";
}
//**
//** main() for testing LTile
//**
public static void main(String[] args)
{
final String letters = "EAIONRTLSUDGBCMPFHVWYKJXQZ";
final int[] values = {1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,5,8,8,10,10};
java.util.List<LTile> lst = new java.util.ArrayList<LTile>();
for (int i = 0; i < letters.length(); ++i)
lst.add(new LTile(letters.charAt(i), values[i]));
for (LTile tile : lst)
System.out.println(tile);
System.out.println();
// test for equals
boolean found = false;
for (int i = 0; i < lst.size()-1; ++i) {
for (int j = i+1; j < lst.size(); ++j) {
if (lst.get(i).equals(lst.get(j))) {
System.out.println("ERROR in equals() found for "
+ lst.get(i) + " and " + lst.get(j));
found = true;
}
}
}
if (!found)
System.out.println("No error in equals().");
}
}
My output is:
[26:E,1]
[26:A,1]
[26:I,1]
[26:O,1]
[26:N,1]
[26:R,1]
[26:T,1]
[26:L,1]
[26:S,1]
[26:U,1]
[26:D,2]
[26:G,2]
[26:B,3]
[26:C,3]
[26:M,3]
[26:P,3]
[26:F,4]
[26:H,4]
[26:V,4]
[26:W,4]
[26:Y,4]
[26:K,5]
[26:J,8]
[26:X,8]
[26:Q,10]
[26:Z,10]
No error in equals()
**The correct output should be:**
[1: E,1]
[2: A,1]
[3: I,1]
[4: O,1]
[5: N,1]
[6: R,1]
[7: T,1]
[8: L,1]
[9: S,1]
[10: U,1]
[11: D,2]
[12: G,2]
[13: B,3]
[14: C,3]
[15: M,3]
[16: P,3]
[17: F,4]
[18: H,4]
[19: V,4]
[20: W,4]
[21: Y,4]
[22: K,5]
[23: J,8]
[24: X,8]
[25: Q,10]
[26: Z,10]
No error in equals().
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
This means that the id value should come from a static data member, not that it should be a static data member. So you need two fields: an instance id field to keep the object's id and a static CURRENT_ID field to keep track of how many objects you have created so far.
public class LTile {
char letter;
private int value;
private int id; // instance id
private static int CURRENT_ID = 0; // static counter from where the instance ids will be drawn
public LTile() {
// Call the other constructor to avoid unnecessary repetition
this('?', 0);
}
public LTile(char letter, int value) {
this.letter = letter;
this.value = value;
this.id = LTile.CURRENT_ID++;
}
// rest of the code
public int getID() {
return this.id;
}
public String toString() {
return "["+this.id+":" + this.letter+","+this.value+"]";
}
}
Note you also need to change getId() and toString() to use the instance id instead of the static counter.

Null pointer exception for Array of Objects

I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.

How to turn static methods into non-static. Small explanation/examples related to java oop

I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.

Categories