Java: Issues with 0 arg constructors and constructors - java

I'm having lots of issues trying to build a constructor where the variables already have default values, and then call the new variables which I set up later on in the TestGuitar class. I've had success compiling my program and printing the default values. I haven't had success retaining the new ones I tried to set up in the newGuitar variable in the TestGuitar class. I know all the issues are coming from my constructors. In this situation I need a 0 arg constructor that creates a default guitar and a new constructor that creates a very specific guitar.
I set up some private variables for the default guitar. I want my program to return the default variables if I never pass anything to then newGuitar variable in the TestGuitar class. If I do pass something, i.e. guitarLength 24.75, I want my program to return that. Even further, I want that new variable to be callable by a getter method. I believe I have the 75% solution, but I need help specifically with the constructor issues at hand. I just don't think I'm grasping the concepts of constructors enough to incorporate a 0 arg and a specific constructor at the same time.
//File name: Guitar.java
//Autor: Michael Joy
//Date: 09/16/2018
//Purpose: Building and testing guitar objects
import java.awt.Color;
import java.util.*;
import java.util.Random;
class Guitar {
//defines the default values for our default guitar if we do not pass anything new to the object
private int numStrings = 6;
private double guitarLength = 28.2;
private String guitarManufacturer = "Gibson";
private Color guitarColor = Color.RED;
private static int i = 1;
private static Random rand = new Random();
//declaring the constructor
public Guitar (){
//all my problems coming from here
this.numStrings = numStrings;
this.guitarLength = guitarLength;
this.guitarManufacturer = guitarManufacturer;
this.guitarColor = guitarColor;
}
public Guitar (int strings, double length, String manufacturer, Color color){
//more problems here
strings = this.numStrings;
length = this.guitarLength;
manufacturer = this.guitarManufacturer;
color = this.guitarColor;
System.out.printf("toString: %s \n ", this);
}
public int getNumStrings() {
return numStrings;
}
public double getGuitarLength() {
return guitarLength;
}
public String getGuitarManufacturer() {
return guitarManufacturer;
}
public Color getGuitarColor(){
return this.guitarColor;
}
public static void playGuitar(){
String[] musicNotes = {"A", "B", "C", "D", "E", "F", "G"};
String[] musicDuration = {"(0.25)","(0.5)","(1)", "(2)","(4)"};
System.out.print("playGuitar: ");
for (i = 1; i < 17; i++){
int index1 = rand.nextInt(musicNotes.length);
int index2 = rand.nextInt(musicDuration.length);
System.out.print(musicNotes[index1]);
System.out.print(musicDuration[index2] + ",");
}
}
public String toString(){
return String.format("%d, %f, %s, %s", numStrings, guitarLength, guitarManufacturer, guitarColor);
}
}
class TestGuitar extends Guitar{
public static void main (String args[] ){
Guitar newGuitar = new Guitar(6, 24.75, "Les Paul", Color.white);
playGuitar();
}
}

Your default initial values belong in the no-args constructor. Then you need to correct the order in which you assign the values in the second constructor. Like,
private int numStrings;
private double guitarLength;
private String guitarManufacturer;
private Color guitarColor;
private static int i = 1;
private static Random rand = new Random();
// declaring the constructor
public Guitar() {
this.numStrings = 6;
this.guitarLength = 28.2;
this.guitarManufacturer = "Gibson";
this.guitarColor = Color.RED;
}
public Guitar(int strings, double length, String manufacturer, Color color) {
this.numStrings = strings;
this.guitarLength = length;
this.guitarManufacturer = manufacturer;
this.guitarColor = color;
System.out.printf("toString: %s \n ", this);
}
Note the first constructor could be re-written to use the other constructor. Like,
// declaring the constructor
public Guitar() {
this(6, 28.2, "Gibson", Color.RED);
}

class Guitar {
private static int i = 1;
private static Random rand = new Random();
private int numStrings;
private double guitarLength ;
private String guitarManufacturer;
private Color guitarColor;
//declaring the constructor
public Guitar (){
//all my problems coming from here
numStrings = 6;
guitarLength = 28.2;
guitarManufacturer = "Gibson";
guitarColor = Color.RED;
}
public Guitar (int strings, double length, String manufacturer, Color color){
this.numStrings = Strings;
this.guitarLength = length;
this.guitarManufacturer = manufacturer;
this.guitarColor = color;
System.out.printf("toString: %s \n ", this);
}
public int getNumStrings() {
return numStrings;
}
public double getGuitarLength() {
return guitarLength;
}
public String getGuitarManufacturer() {
return guitarManufacturer;
}
public Color getGuitarColor(){
return this.guitarColor;
}
public static void playGuitar(){
String[] musicNotes = {"A", "B", "C", "D", "E", "F", "G"};
String[] musicDuration = {"(0.25)","(0.5)","(1)", "(2)","(4)"};
System.out.print("playGuitar: ");
for (i = 1; i < 17; i++){
int index1 = rand.nextInt(musicNotes.length);
int index2 = rand.nextInt(musicDuration.length);
System.out.print(musicNotes[index1]);
System.out.print(musicDuration[index2] + ",");
}
}
public String toString(){
return String.format("%d, %f, %s, %s", numStrings, guitarLength, guitarManufacturer, guitarColor);
}
}
You could also use 1 contructor:
public Guitar (int strings=6, double length=28.2, String manufacturer="Gibson", Color color=Color.RED){
this.numStrings = Strings;
this.guitarLength = length;
this.guitarManufacturer = manufacturer;
this.guitarColor = color;
System.out.printf("toString: %s \n ", this);
}

Related

Type missmatch cannot convert from String to int

The goal of the application is as following: I want to create objects (airplanes) of the class "Flugzeug" (German word for airplane). I want to create an array which refers to the different attributes of the objects.
The problem is (as far as I know) that one single array can only refer to variables of the exact same type.
How can I change my program that it works? Is it inevitable to create an array for each attribute (e.g. for each different type of variable)?
The code:
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug [] airline = new Flugzeug [4];
for (int i = 0; i < 4; i=i+1){
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[0].idNumber = "1";
airline[0].seats = "165";
airline[0].velocity = "890";
airline[0].range = "12600";
airline[1].type = "Boeing 747";
airline[1].idNumber = "2";
airline[1].seats = "416";
airline[1].velocity = "907";
airline[1].range = "12700";
airline[2].type = "Avro RJ 85";
airline[2].idNumber = "3";
airline[2].seats = "93";
airline[2].velocity = "760";
airline[2].range = "2200";
airline[3].type = "Airbus 380";
airline[3].idNumber = "4";
airline[3].seats = "516";
airline[3].velocity = "907";
airline[3].range = "12000";
}
for (int i=0; i < 4; i=i+1) {
airline[i].printInfo();
double time = airline[i].getTime(6320); //distance from Zurich to New York
System.out.println("duration: " + time + " h");
int capacity = airline[i].getCapacity(365);
System.out.println("capacity: " + capacity + " passengers / year");
}
}
}
public class Flugzeug {
String type;
int idNumber;
int seats;
double velocity;
double range;
double distance;
int days;
public void printInfo() {
System.out.println("type: " + this.type);
System.out.println("ID-number: " +this.idNumber);
System.out.println("seats: " + this.seats);
System.out.println("velocity: " + this.velocity);
System.out.println("range: " + this.range);
}
public double getTime (double dist) {
double result = 0;
result = dist / velocity;
double time = result;
return time;
}
public int getCapacity(int days) {
int capacity = seats * days;
return capacity;
}
}
The core of your problem is this:
one single array can only refer to variables of the exact same type.
That is correct (or mostly correct, all elements of an array must have a common base type, but that's not a relevant distinction right now).
But the type inside of your array is Flugzeug, not String!
So each element of the array must be a Flugzeug. That doesn't mean that the fields of that class have to all share a single type (and indeed, as you posted, they don't).
Look at this line:
airline[0].idNumber = "1";
this is almost correct, but since idNumber is an int you must assign it an int value (such as 1) instead:
airline[0].idNumber = 1;
The second (mostly unrelated) problem is that you try to access all 4 Flugzeug instances inside of the loop that creates them. That means when you try to access the second instance after just having created the first one (only!) it will crash:
Replace this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
}
with this:
for (int i = 0; i < 4; i=i+1) {
airline[i] = new Flugzeug ();
}
airline[0].type = "A320";
airline[1].type = "Boeing 747";
airline[2].type = "Avro RJ 85";
airline[3].type = "Airbus 380";
if some type like int,double,long... was used " " ,They almost all become String type
I found two problems with your code.
First, you have declared idNumber as int int idNumber; but while assigning the value you are inserting a string value airline[0].idNumber = "1";.
NOTE: "1" is a string not integer.
The solution here would be airline[0].idNumber = 1;
You need to assign same type of values to every variable as they are declared.
And second, you are creating multiple objects in the loop airline[i] = new Flugzeug (); but overwriting the same single object (stored in the 0th position of the array) everytime. I would suggest to do,
airline[i].type = "A320";
airline[i].idNumber = 1; // Again this should not be "1"
airline[i].seats = 165; // And this should not be "165"
airline[i].velocity = 890; // Same is applicable here
airline[i].range = 12600; // and here
The problem is the variables are not only String type but ints and doubles as well. You need to assign the correct type. In addition you shouldn't access class variables like that, make them private create a constructor with getters and setters.
public class Flugzeug {
private String type;
private int idNumber;
private int seats;
private double velocity;
private double range;
private double distance;
private int days;
public Flugzeug(String type, int idNumber, int seats, double velocity, double range) {
this.type = type;
this.idNumber = idNumber;
this.seats = seats;
this.velocity = velocity;
this.range = range;
}
public double getDistance() {
return this.distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
}
public class Fluggesellschaft {
public static void main(String[] args) {
Flugzeug[] airline = new Flugzeug [4];
airline[0] = new Flugzeug("A320", 1, 165, 890, 12600);
airline[1] = new Flugzeug(...);
}
}

How to store an array of String as an enumeration type

I have made two classes, one is called Card, and the other is Pack.
The Card class has the following attributes :
private String Name;
private int Magic;
private int Cunning;
private int Courage;
private int Wisdom;
private int Temper;
In the Pack class, I have made a file reader methods that read a file on my PC and store each line of it as a string array. So for example this is a part of the text (not code):
Pansy_Parkinson
42
21
18
19
9
Dean_Thomas
40
10
35
22
4
My String array[] stores each line as a different index.
What I want to do, is to convert this String array to array of type Card.
It should store in each index a card with the 6 attributes..
So I suppose I will need to have a method to convert it, and I will have my new 2D Card array based on the previous text this way:
Card [][] ArrayOfCards = new Card [1][5];
Please, any idea how I can do this?
..........................................................
..........................................................
Thank you very much everyone for your valuable helps!
I tried all codes and they seemed great! but I don't know why it's showing me errors either in my main or the methods themselves..
Here is my FileReader class!
import java.io.File;
import java.util.Arrays;
import java.io.*; //To deal with exceptions
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFile {
private Scanner x;
private String Path;
public ReadFile (String ThePath){
Path = ThePath;
}
public String[] openFile() throws IOException /*To throw any errors up the line*/
{
FileReader FR = new FileReader(Path);
BufferedReader TextReader = new BufferedReader(FR);
int NoOfLines = readLines();
String[] TextData = new String[NoOfLines];
for (int i = 0; i < NoOfLines; i++)
TextData[i] = TextReader.readLine(); //Accesses the lines of text and stores them in the array
TextReader.close();
return TextData;
}
int readLines() throws IOException //Return the number of lines in the text
{
FileReader FR2 = new FileReader(Path);
BufferedReader BF = new BufferedReader(FR2);
String ALine;
int NoOfLines = 0;
while ((ALine = BF.readLine()) != null)//Read each line of text & stop when a null value's reached
NoOfLines++;
BF.close();
return NoOfLines;
}
}
And I have just read it yet on main as like this:
public static void main(String[] args) {
// TODO code application logic here
String FileName = "C:/Users/Anwar/Desktop/Potter.txt"; //Path of the file on my PC
try {
ReadFile File = new ReadFile(FileName);
String[] ArrayLines = File.openFile();
for(int i = 0; i < ArrayLines.length; i++)
System.out.println(ArrayLines[i]);
}
catch (IOException e) /*Defiend object of type IOException*/ {
System.out.println(e.getMessage());
}}
Anyone can help me in this?
Because you have a c# tag with your question I decided to give a c# example, which you should be able to convert over to java fairly easily.
Essentially I've created a Card class which has a constructor that accepts the 6 stats about the card. I've kept the fields private as this is how they are in your Question.
I've create a for loop that runs through each of the items in the array, effectively taking 6 items at a time and passing them through to the Card constructor. We're then adding this card to our List of Cards.
I also threw in a quick ToInt() extension to tidy up the Card instantiation.
There are going to be better ways of doing this, but this solves the problem you have presented us with. There is also no error handling in this example.
class Program
{
static void Main(string[] args)
{
var rawData = new string[]{
"Pansy_Parkinson",
"42",
"21",
"18",
"19",
"9",
"Dean_Thomas",
"40",
"10",
"35",
"22",
"4"
};
var Cards = new List<Card>();
for(int i = 0; i < rawData.Length; i+=6)
{
var card = new Card(rawData[0 + i], rawData[1 + i].ToInt(), rawData[2 + i].ToInt(), rawData[3 + i].ToInt(), rawData[4 + i].ToInt(), rawData[5 + i].ToInt());
Cards.Add(card);
}
}
}
public static class StringExtensions
{
public static int ToInt(this string item)
{
return Convert.ToInt32(item);
}
}
public class Card
{
private string Name;
private int Magic;
private int Cunning;
private int Courage;
private int Wisdom;
private int Temper;
public Card(string name, int magic, int cunning, int courage, int wisdom, int temper)
{
Name = name;
Magic = magic;
Cunning = cunning;
Courage = courage;
Wisdom = wisdom;
Temper = temper;
}
}
Maybe try to od it like that:
Create constructor for Card with param String array[][] and which will be the array created from text file and second param which will be the int number that will say where to search for the data for constructor
the constructor should work like this:
Card(String[][] array, int numberForConstructor){
this.name = array[numberForConstructor][0];
this.magic = array[numberForConstructor][1];
this.cunning = array[numberForConstructor][2];
this.courage = array[numberForConstructor][3];
this.temper = array[numberForConstructor][4];
}
then you can use this constructor to put new Card objects to Array, List or anything you want
You should create getter/setter for your class Card, then you can use this function. I don't know which language you use (c# or java) so you will have to adjust the solution bellow.
public class Pack
{
public List<Card> cards = new List<Card>();
public Pack(string filename)
{
// Your parsing function
while ((line = readLine() != null)
{
Card c = new Card();
c.setName(line);
c.setMagic(Convert.ToInt32(readLine());
c.setCunning(Convert.ToInt32(readLine());
c.setCourage(Convert.ToInt32(readLine());
c.setWisdom(Convert.ToInt32(readLine());
c.setTemper(Convert.ToInt32(readLine());
cards.add(c);
}
}
}
Then you to create a new Pack just do the following
Pack p = new Pack("cards.txt");
p.cards[0].getName();
It seams that your input array has one card parameter per line. So I think you are simply looking for something like this:
public static Card[] convert(String[] arr){
if(arr.length % 6 != 0){
System.out.println("error in data");
return null;
}
Card[] res = new Card[arr.length / 6];
for(int i = 0; i < res.length; i++){
String Name = arr[(i * 6) + 0];
int Magic = Integer.parseInt(arr[(i * 6) + 1]);
int Cunning = Integer.parseInt(arr[(i * 6) + 2]);
int Courage = Integer.parseInt(arr[(i * 6) + 3]);
int Wisdom = Integer.parseInt(arr[(i * 6) + 4]);
int Temper = Integer.parseInt(arr[(i * 6) + 5]);
res[i] = new Card(Name, Magic, Cunning, Courage, Wisdom, Temper);
}
return res;
}
This can work:
public Card ConvertArrayToCard(string[] array)
{
Card card = new Card;
card.Name = array[0];
card.Magic= array[1];
card.Cunning= array[2];
card.Courage= array[3];
card.Wisdom= array[4];
card.Temper= array[5];
}
Quite a few answers.. Here is another one.
Your class;
public class Pack
{
public string Name { get; set; }
public int Magic { get; set; }
public int Cunning { get; set; }
public int Courage { get; set; }
public int Wisdom { get; set; }
public int Temper { get; set; }
}
Then the logic. There is some built in defensive coding mechanism in this. I will let you figure that out.
var lines = File.ReadAllLines(#"C:\temp2.txt");
List<Pack> mypack = new List<Pack>();
Pack member = null;
int count = 0;
foreach (var line in lines)
{
int val;
count = (!int.TryParse(line, out val)) ? 0 : count + 1;
switch (count)
{
case 0:
member = new Pack() { Name = line.Trim() };
break;
case 1:
member.Magic = val;
break;
case 2:
member.Cunning = val;
break;
case 3:
member.Courage = val;
break;
case 4:
member.Wisdom = val;
break;
case 5:
member.Temper = val;
mypack.Add(member);
break;
}
}
return mypack;

how to make an object move around a 2d grid array on its own towards other objects in java

OK so I have recently got my program to the point where it is allmost working, however I cant seem to figure out how to make my bug object move.
I have a class called AWorld that is populated with instances of a class method Randfood (ints between 0 and 9) in randomly placed possitions within the grid. It is also passed and instance of my class ABug as an attribute that is placed into the grip according to user input. my problem is I wish to make it move towards the food objects (my ints between 0-9) and when its next to them to have its energy level increased accordingly. it needs to only move towards an object when its within a set distance from it. i.e. 3 spaces in any direction, else just move randomly. my issue is i cant seem to figure out how to do that with my current code setup.
AWorld Class:
package finalversion2;
import java.util.Arrays;
import java.util.Random;
public class AWorld {
int x[] = new int[10], y[] = new int[10];
int row = 25;
int column = 25;
char[][] map;
public static int RandFood(int min, int max) {
Random rand = new Random(); // Initializes the random function.
int RandNum = rand.nextInt((max - min) + 1) + min; //generates a random number within the max and min ranges
return RandNum; //returns the random number
}
//Constructor
//Sets up map array for the AWorld object
//uses a bug that is passed to it
public AWorld(ABug bug) {
ABug bug1 = bug;
map = new char[row][column];
for (int i = 0; i < row; i++) {
for (int x1 = 0; x1 < column; x1++) {
map[i][x1] = ' ';
}
}
for (int i = 0; i < column; i++) {
Random rand = new Random();
int x = rand.nextInt(row);
int y = rand.nextInt(column);
map[x][y] = (char) RandFood(48, 57);
map[bug1.getHPossistion()][bug1.getVPossistion()] = bug1.getSymbol(); // gets the bugs x and y possistion in the array (user defined) and puts it into the symbol variable
}
}
public void PrintWorld() {
for (int i = 0; i < row; i++) //these next two for loops print the array to the screen
{
System.out.print("|");
for (int x1 = 0; x1 < column; x1++) {
System.out.print(map[i][x1]);
}
System.out.println("|");
}
}
}
ABug:
package finalversion2;
public class ABug
{
public static void main(){
}
private String species = new String(); //instance variables (defines data of object)
private String name = new String();
private String description = new String();
private char symbol;
private int hPossistion, vPossistion, energy, iD;
public ABug(){
}
public ABug (String s, String n, String d, int h, int v, int e, int i){
this.species = s;
this.name = n;
this.description = d;
this.symbol = s.charAt(0);
this.hPossistion = h;
this.vPossistion = v;
this.energy = e;
this.iD = i;
}
//setters
public void setSpecies(String s){
this.species = s;
}
public void setName(String n){
this.name = n;
}
public void setSymbol(char symbol){
this.symbol = symbol;
}
public void setHPossistion(int x){
this.hPossistion = x;
}
public void setVPossistion(int y){
this.vPossistion = y;
}
public void setEnergy(int energy){
this.energy = energy;
}
public void setID(int i){
this.iD = i;
}
public void setDescription(String d){
this.description = d;
}
//getters
public String getSpecies(){
return this.species;
}
public String getName(){
return this.name;
}
public char getSymbol(){
return this.symbol;
}
public int getHPossistion(){
return this.hPossistion;
}
public int getVPossistion(){
return this.vPossistion;
}
public int getEnergy(){
return this.energy;
}
public int getID(){
return this.iD;
}
public String getDescription(){
return this.description;
}
public String toString(){
String BugData;
BugData = name + " " + symbol + "\n" + species + "\n" + description;
return BugData;
}
}
enum Direction:
package finalversion2;
public enum Direction {
NORTH, EAST, SOUTH, WEST;
}
now im guessing I need to redraw my map each time i wish it to move using my enum based on a boolean response, i.e. call the printworld method but randomly move the bug. but wont that reprint my random ints?
please help. im very new to java.
Cheers in advance.

Creating a deck of cards and shuffling them

I have been stuck on this for sometime now, the objective is to create an array to hold the cards in, once I do create the array print them out the only card that is printing is king of hearts. Why is it not iterating?
public class Card
{
// Card suits (provided for your convenience - use is optional)
public static final int SPADES = 0;
public static final int HEARTS = 1;
public static final int CLUBS = 2;
public static final int DIAMONDS = 3;
// Card faces (provided for your convenience - use is optional)
public static final int ACE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
public static final int FOUR = 4;
public static final int FIVE = 5;
public static final int SIX = 6;
public static final int SEVEN = 7;
public static final int EIGHT = 8;
public static final int NINE = 9;
public static final int TEN = 10;
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
// define fields here
private static int suit;
private static int val;
private String[] suits = {"Clubs", "Spades", "Diamonds", "Hearts"};
private String[] vals = {"Ace","2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King" };
// This constructor builds a card with the given suit and face, turned face down.
public Card(int suit, int val)
{
this.val = val;
this.suit = suit;
}
public #Override String toString()
{
return vals[val] + " Of " + suits[suit];
}
// This method retrieves the suit (spades, hearts, etc.) of this card.
public int getSuit()
{
return this.suit;
}
// This method retrieves the face (ace through king) of this card.
public int getFace()
{
// return this.val;
switch(val)
{
case 0 : return 1;
case 1 : return 2;
case 2 : return 3;
case 3 : return 4;
case 5 : return 6;
case 6 : return 7;
case 7 : return 8;
case 8 : return 9;
case 9 : return 10;
case 10 : return 10;
case 12 : return 10;
default : return 0;
}
}
}`
import java.util.ArrayList;
import java.util.Random;
// This class represents the deck of cards from which cards are dealt to players.
public class Deck
{
//array
public static Card[] cards;
// private static ArrayList<Card> cards;
int i;
int counter;
// This constructor builds a deck of 52 cards.
Deck()
{
i = 51;
//array implementation
cards = new Card[52];
int x = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13;j++)
{
//Array implementation
cards[x] = new Card(i,j);
x++;
}
}
}
// This method takes the top card off the deck and returns it.
public Card deal()
{
//Array implementation
int index = 0;
Card temp = cards[index];
return temp;
}
// this method returns true if there are no more cards to deal, false otherwise
public boolean isEmpty()
{
if(cards.length == 0)
{
return true;
}
return false;
}
//this method puts the deck int some random order
// public void shuffle()
// {
// for(int i = 51; i > 0; i--)
// {
// int rand = (int) (Math.random() * (i+1));
// Card temp = this.cards[i];
// this.cards[i] = cards[rand];
// cards[rand] = temp;
// }
//
// }
}
public class BlackJack extends Deck
{
public static void main(String []args)
{
System.out.println("Ready to play a game of BlackJack?");
Deck deck = new Deck();
for(int i = 0; i < cards.length;i++)
{
System.out.println(cards[i]);
}
Problem is caused by the following:
// define fields here
private static int suit;
private static int val;
because they are static, all Card instances share these, so they will all have the last value they were set to. Remove the static.
To give you a little hint how you might make the code even easier to read/maintain:
use enums instead of constants. You can give them constructors/member variables just like classes
use for-each-loops, it's way easier to read and prevents the usual off-by-1 problems
type 'static' BEFORE all other modifiers and keep all static variables and members separate from any non-static content. this way you can never mix them up by accident
Bad / unusual sides of this code are:
I use static nested enums and classes. Usually each of those should go into its own file and be non-static
I like to prefix my variables according to their scope so I cannot mess em up: pXxx for Parameter, sXxx for static variables, mXxxx for members, no prefix for method variables
public class CardGame {
static public enum SuitType {
SPADES, HEARTS, CLUBS, DIAMONDS
}
static public enum FaceType {
ACE("Ace", 1), //
TWO("2", 2), //
THREE("3", 3), //
FOUR("4", 4), //
FIVE("5", 5), //
SIX("6", 6), //
SEVEN("7", 7), //
EIGHT("8", 8), //
NINE("9", 9), //
TEN("10", 10), //
JACK("Jack", 11), //
QUEEN("Queen", 12), //
KING("King", 13), //
;
private final String mName;
private final int mValue;
private FaceType(final String pName, final int pValue) {
mName = pName;
mValue = pValue;
}
public String getName() {
return mName;
}
public int getValue() {
return mValue;
}
public int getValue_alternative() {
return ordinal() + 1; // ordinal is the index of the enum, starting at ace=0 ... king=12
// sorting and comparing of suits could also be done by .ordinal() if need be
}
}
static public class Card {
private final SuitType mSuit;
private final FaceType mFace;
public Card(final SuitType pSuit, final FaceType pFace) {
mSuit = pSuit;
mFace = pFace;
}
public SuitType getSuit() {
return mSuit;
}
public FaceType getFace() {
return mFace;
}
#Override public String toString() {
return mFace.getName() + " of " + mSuit + " - " + mFace.getValue() + (mFace.getValue() > 1 ? " points" : " point");
}
}
static public class Deck {
private final ArrayList<Card> mCards;
public Deck() {
mCards = createFullDeck();
}
private ArrayList<Card> createFullDeck() { // can also be static as it dowes not use member cariables => potential factory method
final ArrayList<Card> ret = new ArrayList<>();
for (final SuitType suit : SuitType.values()) {
for (final FaceType face : FaceType.values()) {
final Card c = new Card(suit, face);
ret.add(c);
}
}
return ret;
}
public void shuffleRandomly() {
final ArrayList<Card> tempList = new ArrayList<>();
tempList.addAll(mCards);
mCards.clear();
while (tempList.size() > 0) {
final int index = (int) (Math.random() * tempList.size());
final Card card = tempList.remove(index);
mCards.add(card);
}
}
public void print() {
System.out.println(" - - - DECK BEGINS - - - ");
int counter = 0;
for (final Card c : mCards) {
System.out.println("\t" + c);
++counter;
}
System.out.println("> Printed " + counter + " cards.");
System.out.println(" - - - DECK ENDS - - - ");
}
}
public static void main(final String[] args) {
final Deck d = new Deck();
d.print();
d.shuffleRandomly();
d.print();
}
}

Why is there an NullPointerException?

I am trying to mommertary use a string and convert it to an int to compare the first first column and all the rows with the all of the numbers within the string typed in. When I type in a number, I get a NullPointerException. The thing is, I don't understand why the compiler is telling me this when I feel like I have declared all my objects properly. please help!
import java.util.ArrayList;
public class Decoder
{
private int[][] zipdecoder;
private ArrayList<Integer> zipcode;
private String finalCode;
private String bars;
private int place;
public Decoder()
{
int[][] zipdecoder = new int[][]{
{1,0,0,0,1,1},
{2,0,0,1,0,1},
{3,0,0,1,1,1},
{4,0,1,0,0,0},
{5,0,1,0,1,1},
{6,0,1,1,0,0},
{7,1,0,0,0,0},
{8,1,0,0,1,1},
{9,1,0,1,0,0},
{0,1,1,0,0,0}
};
zipcode = new ArrayList<Integer>();
}
public void insertToArray(String zip)
{
int count = 0;
for(int i = 1; i<zip.length()+1;i++)
{
String piece = zip.substring(count, i);
int number = Integer.parseInt(piece);
for(int j = 0;j<10;j++)
{
if(number == zipdecoder[j][0]){
for(int a = 1;a<5;a++)
{
zipcode.add(place,zipdecoder[j][a]);
place++;
}
}
count++;
}
}
}
You're not initializing the class member zipdecoder but a new local variable (with the same name) in the constructor.
Change this
int[][] zipdecoder = new int[][]{
to
zipdecoder = new int[][]{
and it should work.

Categories

Resources