getting the following error message when trying to use toString to display array:
java.lang.NullPointerException
Here's the code:
import java.util.Scanner;
import java.util.Random;
public class RandomArray {
private int data[];
private int value;
public RandomArray(int x)
{
Random gen = new Random();
int[] data = new int[x];
for (int index = 0; index<x; index ++)
data[index] = gen.nextInt(x);
}
public String toString()
{
String output = "";
for(int i = 0; i<data.length; i++)
{
output +=data[i];
}
return output;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x;
int data;
System.out.println("please enter the number of integers you would like to create an array for");
x = scan.nextInt();
RandomArray table = new RandomArray(x);
table.toString();
From what I can tell this error means the toString is throwing null? But I do not know why that is, can anyone help me out?
You are redeclaring your data array which is hiding the one you are filling.
Random gen = new Random();
int[] data = new int[x]; // remove the int[] declaration
Also, it might be easier if you just did the following:
// your toString method
public String toString() {
return Arrays.toString(data);
}
In response to your question, you can do this.
int[] data; // you did this - leave it alone
// and later you should do this.
public RandomArray(int x) {
Random gen = new Random();
data = new int[x]; // designated as an array above
for (int index = 0; index<x; index ++)
data[index] = gen.nextInt(x);
}
}
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);
}
I've made a table with geometrical figures and a for loop for printing out the name of figures that have right angle, but I would like to print out one random name for this figure that matches the condition and if it's possible create another table that contains only figures that match the condition. I was trying to use some method from java.util.Random but I couldn't find out how. I'll be thankful for Your help:
import java.util.Random;
public class rectangularFigures {
private String name;
private boolean rightAngle;
public String getName() {
return name;
}
public rectangularFigures(String name, boolean rightAngle) {
this.name = name;
this.rightAngle = rightAngle;
}
public static void main(String[] args) {
rectangularFigures[] lOFigures = new rectangularFigures[4];
lOFigures[0] = new rectangularFigures("whell", false);
lOFigures[1] = new rectangularFigures("square", true);
lOFigures[2] = new rectangularFigures("rhombus", false);
lOFigures[3] = new rectangularFigures("rectangle", true);
for (int i = 0; i < lOFigures.length; i++) {
{
if (lOFigures[i].rightAngle) {
System.out.println(lOFigures[i].name);
}
}
}
}
}
The simplest way is to use java streams:
rectangularFigures[] onlyRightAngles = Arrays.stream(lOFigures).filter(x -> x.rightAngle).toArray(rectangularFigures[]::new);
rectangularFigures randomElement = onlyRightAngles[new Random().nextInt(onlyRightAngles.length)];
System.out.println(randomElement.name);
But if for some reasons you can't use streams, i suggest to use ArrayList and traditional foreach loop:
List<rectangularFigures> onlyRightAngles = new ArrayList<>();
for (rectangularFigures figure : lOFigures) {
if (figure.rightAngle) onlyRightAngles.add(figure);
}
rectangularFigures randomElement = onlyRightAngles.get(new Random().nextInt(onlyRightAngles.size()));
System.out.println(randomElement.name);
This is just a small example but it can be improved:
Random r = new Random();
for (int i = 0; i < lOFigures.length; i++) {
{
int f = r.nextInt(4);
if (lOFigures[f].rightAngle) {
System.out.println(lOFigures[f].name);
}
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am working on a homework about arrays and while loop in java.
The question is to create a method called public int getPopulation(String province) which returns the population of the province. If there is no such province, return a constant called NO_SUCH_PROVINCE, which is an int set to -1. But I cannot get what I want.
public class Country {
public static final int ON = 0;
public static final int QC = 1;
public static final int BC = 2;
public static final int AB = 3;
public static final int MB = 4;
public static final int NO_SUCH_PROVINCE = -1;
private String[] provinces;
private int[] population;
public Country() {
provinces = new String[5];
provinces[0] = "Ontario";
provinces[1] = "Quebec";
provinces[2] = "British Columbia";
provinces[3] = "Alberta";
provinces[4] = "Manitoba";
population = new int[5];
population[ON] = 12851821;
population[QC] = 7903001;
population[BC] = 4400057;
population[AB] = 3645257;
population[MB] = 1208268;
}
public int getPopulation(String province) {
int i = 0;
int temp = 0;
while(i < provinces.length) {
if(province == provinces[i]) {
temp = population[i];
}else {
temp = NO_SUCH_PROVINCE;
}
i++;
}
return temp;
}
There is an issue with your search algorithm. It keeps going after it finds the solution and then overwrites the correct value. This here, when it finds the value, immediately returns the value and leaves the method. If it cannot find any value, it then returns NO_SUCH_PROVINCE.
The other issue is that noted by Scary Wombat, which is that your code does not compare Strings correctly to find a match.
public int getPopulation(String province) {
for (int i = 0; i < provinces.length; i++) { // For objects, always use .equals()
if (province.equals(provinces[i])) { return population[i]; }
}
return NO_SUCH_PROVINCE;
}
Of course, this would be much simpler if one could simply use a HashMap<String, Integer> that stores all the data like a dictionary.
I want to make a 2D array of Arrays, each filled with another object. What I have so far is:
class CustomCache{
boolean dirty = false;
int age = 0;
String addr;
public CustomCache(boolean a, String b, int c){
dirty = a;
addr = b;
age = c;
}
}
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
Setup[][] array = new Setup[numSets][numBlocks];
for(int i=0; i<numSets; i++){
for(int j=0; j<numBlocks; j++){
array[i][j] = new Setup(wpb);
for(int k=0; k<wpb; k++){
array[i][j].wpbArray[k] = new CustomCache(false, "", 0);
}
}//end inner for
}//end outer loop
I keep getting a
java.lang.ArrayIndexOutOfBoundsException: 0
Which means the array is empty. Any idea of how to fix it?
This is the problem:
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
This line:
CustomCache[] wpbArray = new CustomCache[wpb];
runs before the body of the constructor - while wpb is still 0. You want:
class Setup {
int wpb;
CustomCache[] wpbArray;
public Setup(int a) {
wpb = a;
wpbArray = new CustomCache[wpb];
}
}
(I also suggest changing to more meaningful names, and using private final fields, but that's a different matter.)