Issue with array of an object - java

I am learning java and was trying some stuff. This is what I am trying to do.
I am trying to create an table of an array of an object.
e.g. I am creating an object called animal by which i can add any number of animal and its breed on user choice.
package tt;
import java.util.Scanner;
public class animal {
String aname;
String abreed;
public animal() {
mainprog aa = new mainprog();
System.out.printf("eneter name of your %s..\n", aa.Animalcat);
Scanner name = new Scanner(System.in);
aname = name.nextLine();
System.out.printf("eneter breed of your %s..\n", aa.Animalcat);
Scanner breed = new Scanner(System.in);
abreed = breed.nextLine();
}
public String getbreed() {
return abreed;
}
public String getname() {
return aname;
}
}
So the main program ask for how many animals I want to add.
package tt;
import java.util.Scanner;
public class mainprog {
public static String Animalcat;
public static void main(String[] args) {
System.out.println("How many animals you want to add..");
Scanner an = new Scanner(System.in);
int animalNumbers = an.nextInt();
animal[][] addAnimal = new animal[animalNumbers][1];
animaltype[] at = new animaltype[animalNumbers];
for (int i = 0; i < animalNumbers; i++) {
at[i] = new animaltype();
Animalcat = at[i].getAnimalType();
for (int j = 0; j < 1; j++) {
addAnimal[i][j] = new animal();
}
}
Display(addAnimal, at);
}
public static void Display(animal x[][], animaltype y[]) {
System.out.println("Your animals are..");
for (int m = 0; m < x.length; m++) {
System.out.printf("Following are the name and the breed of %s ",
y[m].getAnimalType());
System.out.println();
for (int n = 0; n < x[m].length; n++) {
System.out.printf(" %s", x[m][n].aname);
System.out.printf(" %s", x[m][n].abreed);
System.out.println();
}
}
}
}
package tt;
import java.util.Scanner;
public class animaltype {
String animalType;
public animaltype() {
System.out.println("What kind of animal you want to add..");
Scanner at = new Scanner(System.in);
animalType = at.nextLine();
}
public String getAnimalType(){
return animalType;
}
}
The issue I have here is I can ask for how many types of animals I want to add but I can't control how many animals of that type I want to add.
While adding animal I can only add 1 number of animal manually by declaring it as [1] and can't by user input.
addAnimal = new animal[animalNumbers][1];
The problem in if I can do that by declaring animal[][] addAnimal = null; and then later initialize it with like:
animal[][] addAnimal = new animal[animalNumbers][animaltypenumbers];
But I get NullPointerException all time. Is there anyway I can have this done?

When you create an array, it will be filled by the default value of the element it contains. Since Animal is an Object, then it will be filled by null values, and you cannot use any variable which has null value. Since you're just filling animal[i][0] in your current code, you won't get any problem. But it will appear when you try to access to animal[i][1]. This happens in Display method:
public static void Display(animal x[][], animaltype y[]) {
System.out.println("Your animals are..");
for (int m = 0; m < x.length; m++) {
System.out.printf("Following are the name and the breed of %s ",
y[m].getAnimalType());
System.out.println();
for (int n = 0; n < x[m].length; n++) {
//you only filled elements in x[m][0]
//x[m][n] when n > 0 is null
//so you will get NullPointerException
System.out.printf(" %s", x[m][n].aname);
System.out.printf(" %s", x[m][n].abreed);
System.out.println();
}
}
}
A better option:
Use Animal[] addAnimal instead, you don't need it to have it as an array of arrays:
public static void main(String[] args) {
System.out.println("How many animals you want to add..");
Scanner an = new Scanner(System.in);
int animalNumbers = an.nextInt();
animal[] addAnimal = new animal[animalNumbers];
animaltype[] at = new animaltype[animalNumbers];
for (int i = 0; i < animalNumbers; i++) {
//at[i] = new animaltype();
//Animalcat = at[i].getAnimalType();
Animalcat = new animaltype();
//for (int j = 0; j < 1; j++) {
// addAnimal[i][j] = new animal();
//}
addAnimal[i] = Animalcat;
}
Display(addAnimal, at);
}
//modify Display method accordingly
A better option:
Use List<Animal> backed by ArrayList<Animal> instead of Animal[]. List let's you handle a list of elements that grows dynamically.
public static void main(String[] args) {
System.out.println("How many animals you want to add..");
Scanner an = new Scanner(System.in);
int animalNumbers = an.nextInt();
List<Animal> animals = new ArrayList<Animal>();
for (int i = 0; i < animalNumbers; i++) {
Animalcat = new animaltype();
animals.add(Animalcat);
}
Display(animals);
}
//modify Display method accordingly

Related

Sorting arrays from lowest to highest numbers with ratios using methods in Java

I am writing a program that takes in the number of ingredients. The prog
This is my code:
import java.util.Scanner;
public class Restaurant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
}
Change this sortCalories function to the one below. Also you need to pass price array as second parameter like this sortCalories(calories,price, ingredientName);:
public static void sortCalories(double[] calories,double[] price, String[] ingredientName) {
double temp;
String temp1;
for (int p=0; p<calories.length; p++) {
for (int j=p+1; j<calories.length; j++) {
if(calories[p]/price[p]>calories[j]/price[j]) {
temp = calories[p];
calories[p] = calories[j];
calories[j] = temp;
temp = price[p];
price[p] = price[j];
price[j] = temp;
temp1 = ingredientName[p];
ingredientName[p] = ingredientName[j];
ingredientName[j] = temp1;
}
}
}
}

How to implement two dimensional object array?

I want to implement a two-dimensional array using user input. I have a Book class. It has two variables: int price and String name. I want to store 5 books information in a two-dimensional array. Book class code is below:
public class Book {
String name;
int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
Main Class code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int l = 5;
Book[][] bk = new Book[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
// here i want to take user input.
System.out.println("Enter Song: ");
String sname = in.next();
System.out.println("Enter price: ");
int sprice = in.nextInt();
// in this line i am getting type
// error int can't convert to string
song[i][j] = song[sname][price];
}
}
}
You never declared the array song, maybe you wanted to write
bk[i][j] = ...
Now you want to create a new "Book" for every sname and sprice that you read, so you have two options:
1) In each iteration create a new empty Book
Book tmp = new Book();
then you set his Name and his Price
tmp.setName(sname);
tmp.setPrice(sprice);
and then you assign the new Book to the current element of bk
bk[i][j] = tmp;
or
2) Add a constructor to the class Book that has Name and Price as parameters
public Book(String n, int p){
name = n;
price = p;
}
and use it to instantly create a new Book and assign it to the current element of bk
bk[i][j] = new Book(sname, sprice);
So what you require is Book[String name][int price]. That is not how 2D arrays work.
While declaring:
int l = 5;
Book[][] bk = new Book[l][l];
You are implementing a 2D Book array that can have 25 book records.
1D array of Books is sufficient for your requirements.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int l = 25;//any size you can have
Book[] bk = new Book[l];
for (int i = 0; i < l; i++) {
System.out.println("Enter Song: ");
String sname = in.next();
System.out.println("Enter price: ");
int sprice = in.nextInt();
Book book = new Book();
book.setName(sname);
book.setprice(sprice);
bk[i] = book;
}
}

Calling a variable into another method in java

Does anyone know how to call a variable into another method? Doing an assignment for school and really struggling. (Variable that I want to call is arrayOfEarth by the way.)
public static void readDataArray(String filename) throws FileNotFoundException {
Scanner input = new Scanner(new BufferedReader(new FileReader("sample.xyz")));
int rows = 2500000;
int columns = 3;
double[][] arrayOfEarth = new double[rows][columns];
while (input.hasNextLine()) {
for (int a = 0; a < arrayOfEarth.length; a++) {
String[] line = input.nextLine().trim().split("/t ");
for (int b = 0; b < line.length; b++) {
arrayOfEarth[a][b] = Double.parseDouble(line[b]);
}
}
}
System.out.println(Arrays.deepToString(arrayOfEarth));
}
public static List<Double> CoordinatesAbove(double altitude) {
List<Double> CoordinatesAbove = new ArrayList<>();
for (int c = 0; c < arrayOfEarth.length; c++) {
CoordinatesAbove.add(arrayOfEarth[c][2]);
}
CoordinatesAbove.removeIf(d -> d < altitude);
return CoordinatesAbove;
}
Just move it to the class level and make it static (otherwise the static method can't use it)
private static double[][] arrayOfEarth;
public static void readDataArray(String filename) throws FileNotFoundException {
Scanner input = new Scanner(new BufferedReader(new FileReader("sample.xyz")));
int rows = 2500000;
int columns = 3;
arrayOfEarth = new double[rows][columns];
while (input.hasNextLine()) {
for (int a = 0; a < arrayOfEarth.length; a++) {
String[] line = input.nextLine().trim().split("/t ");
for (int b = 0; b < line.length; b++) {
arrayOfEarth[a][b] = Double.parseDouble(line[b]);
}
}
}
System.out.println(Arrays.deepToString(arrayOfEarth));
}
public static List<Double> CoordinatesAbove(double altitude) {
List<Double> CoordinatesAbove = new ArrayList<>();
for (int c = 0; c < arrayOfEarth.length; c++) {
CoordinatesAbove.add(arrayOfEarth[c][2]);
}
CoordinatesAbove.removeIf(d -> d < altitude);
return CoordinatesAbove;
}
Make your readDataArray method return the value to the caller, and have whoever is calling the CoordinatesAbove method pass the value to it.
To return the value and to accept it as a parameter:
public static double[][] readDataArray(String filename) throws FileNotFoundException {
...
System.out.println(Arrays.deepToString(arrayOfEarth));
return arrayOfEarth;
}
public static List<Double> CoordinatesAbove(double altitude, double[][] arrayOfEarth) {
...
}
To capture the return value of readDataArray and to pass it to CoordinatesAbove:
double[][] arrayOfEarth = readDataArray(...)
List<Double> list = CoordinatesAbove(altitude, arrayOfEarth);
It is arguably better to make the flow of information explicit like this, than hiding the flow by writing the results to a common global variable in one method and reading the variable in the other.

printing a toString() method output in a test class

Hi guys I have been making a test class for my word puzzle game and the out put is printing the objects reference number to the object. Anyone got the solution to print the return statement of the object.
Output:
Generator stats: word-puzzles generated from words of length 3
Puzzle.WordPuzzleGenerator#c68c3Puzzle.WordPuzzleGenerator#b2002fPuzzle.WordPuzzleGenerator#2a4983Puzzle.WordPuzzleGenerator#406199Puzzle.WordPuzzleGenerator#c7b00cPuzzle.WordPuzzleGenerator#1f6f296Puzzle.WordPuzzleGenerator#1df5a8fPuzzle.WordPuzzleGenerator#b2a2d8Puzzle.WordPuzzleGenerator#1e13d52Puzzle.WordPuzzleGenerator#80fa6f
Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
int sizeTest1 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest1);
for (int i = 0; i < 10; i++) {
WordPuzzleGenerator puzzle = new WordPuzzleGenerator(sizeTest1);
System.out.print(puzzle);
}
int sizeTest2 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest2);
for (int i = 0; i < 10; i++) {
new WordPuzzleGenerator(sizeTest2);
}
}
}
Main program:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public WordPuzzleGenerator(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord) && !puzzleListY.contains(randomXWord)) {
finished = false;
break;
}
puzzleListX.add(randomXWord);
}
}
toString(puzzleListX, puzzleListY);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
public static String toString(ArrayList<String> ArrayList1, ArrayList<String> ArrayList2){
StringBuilder group1 = new StringBuilder();
for (int i = 0; i < ArrayList1.size(); i++) {
group1.append(ArrayList1.get(i) + " ");
}
String wordsInString1 = group1.toString();
StringBuilder group2 = new StringBuilder();
for (int i = 0; i < ArrayList2.size(); i++) {
group2.append(ArrayList2.get(i) + " ");
}
String wordsInString2 = group2.toString();
return String.format("\t( %s) ( %s)", wordsInString1, wordsInString2);
}
}
Your WordPuzzleGenerator class does not override Object's toString. Instead it contains a static toString method with a different signature.
You need a method of this signature in your WordPuzzleGenerator class :
#Override
public String toString()
{
...
}
After taking another look, it appers your WordPuzzleGenerator has only static methods and no instance members, so it's unclear what you expect toString to return, or in other words - it's not clear what System.out.print(puzzle); is expected to print.
EDIT:
If you want toString() to print the Lists created in your constructor, you should make them instance members :
ArrayList<String> puzzleListY;
ArrayList<String> puzzleListX;
public WordPuzzleGenerator(int size) throws FileNotFoundException {
puzzleListY = new ArrayList<String>();
puzzleListX = new ArrayList<String>();
...
}
Then you can override toString like this :
#Override
public String toString()
{
return WordPuzzleGenerator.toString (puzzleListX,puzzleListY);
}
you'll have to override the toString method of your objects, since your object inheris from java object
#Override
public String toString(){
\\mystring build up...
return mystring;
notice the override annotation, thats what does the trick ;)
happy coding!
try to override 'toString' method in your class as follows:
#Override
public String toString()
{
//your code
}

What am I doing wrong with using arrays?

I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH

Categories