Can't use toString to display array - java

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);
}
}

Related

Scope of the array:

Here I am trying to find the max and min number entered into the array so I'm using a min and a max method(not declared yet) but I'm not quite sure how to access my array in these methods as the array userArray and array are not in the scope of the method and can't be accessed. can someone help me out?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
//Method to take user input
public int[] getUserData() {
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
// Create variable to store user's desired number of values
int totalNumbers = keyboard.nextInt();
// Declare and initialze an array
int[] userArray = new int[totalNumbers];
// Create a loop to ask for values from the user
// Within the loop, store user input in the array
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("Enter number " + x);
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element: array){
System.out.println(element);
}
}
}
public int minNumber(int[] userDataArray) {
// use userDataArray here
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // pass userDataArray as argument
}

Missing Return Statement in Java Recursive Function

I'm trying to generate a list of 25 non-repeating random numbers in Java, and I keep getting the Missing Return Statement error. As can be seen, I tried putting return before calling the method within itself. Not sure what's missing. It also didn't work with just the return (rando)
import java.util.*;
public class arrayList{
ArrayList<Integer> checkRandom;
ArrayList<Integer> array4;
ArrayList<Integer> array2;
ArrayList<Integer> array3;
public int addRandom(){
Random rnd = new Random();
int b=0;
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
for (int j=0;j<26;j++){
int right;
right = checkRandom.get(j);
System.out.println(right);
}
return -1;
}
public static void main(String args[]){
arrayList randomGen = new arrayList();
randomGen.addRandom();
}
}
Exception in thread "main" java.lang.NullPointerException
at arrayList.addRandom(arrayList.java:14)
at arrayList.main(arrayList.java:37)
I'd suggest you use a much simpler method using Java 8 streams. For example, to create an array of 26 distinct random integers betweeen 0 and 100:
int[] randomArray = new Random().ints(0, 101).distinct().limit(26).toArray();
To explain in a bit more detail, this statement can be interpreted as: create a random number generator, use it to generate an endless stream of random numbers between 0 and 100, remove any duplicates, get the first 26 numbers in the stream and convert them to an int array.
Streams are incredibly powerful. Once your generator is in this form it's trivial to add a sorted operator or a filter, or to collect them into a List or Map.
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Random rand = new Random();
while (list.size() < 25) {
int index = rand.nextInt(101);
if (!list.contains(index)) {
list.add(index);
}
}
System.out.println(list);
}
}
Initialize a method local variable b inside your addRandom method and reassign it in your for loop finally return variable b.
public int addRandom(){
Random rnd = new Random();
int b=0;
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
b= addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
b=rando;
}
}
return b;
}
Your method
public int addRandom(){
Random rnd = new Random();
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
}
does not have a return statement at the end. The method signature states you must return an integer. The compiler does not know that the for statement will be executed until runtime. Thus, you have to handle the case where the for loop is not executed. Since you can tell it will be executed every time, adding a return -1; before the end of the method will solve your problem.
i.e.
public int addRandom(){
Random rnd = new Random();
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
return -1;
}
You can call the method by creating an instance of the class i.e.
arrayList randomGen = new arrayList();
randomGen.addRandom();
Btw, its standard in java to name your classes CamelCased. i.e. ArrayList. Although, you may want to rename it something else so you don't confuse your class with java.util.ArrayList (a popular java class)
If you want use recursion, you don't need loops. for example:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Test {
List<Integer> randomList = new ArrayList<Integer>();
Random rnd = new Random(); // do not create new Random object in each function call.
final static int LIST_SIZE = 25;
public void addRandom(List someList) {
if (randomList.size() < LIST_SIZE) {
int random = rnd.nextInt(101); // LIST_SIZE must be lesser than 101 otherwise you will got infinite recursion.
if (!randomList.contains(random)) {
randomList.add(random);
someList.add(random);
}
addRandom(someList);
}
}
public static void main(String args[]) {
Test test = new Test();
List<Integer> array4 = new ArrayList<Integer>();
test.addRandom(array4);
for (Integer value : array4) {
System.out.println(value);
}
}
}

Generate random integers with a range and place them into this array

I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}

Random Data Analyzer

I'm creating a program that will generate 100 random numbers between 1 and 1000, add them to a list, and then sum up those numbers. Here's my code:
public class Iteration {
public static void main (String [] args){
private int RandomDataAnalyzer(int Rando) {
Random rand = new Random();
List<Integer> NumList = new ArrayList<Integer>();
for (int i=0;i<=100;i++){
Rando = rand.nextInt(1001);
NumList.add(Rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
Rando = rand.nextInt(100);
sum = sum + Rando;
}
return sum;
}
}
}
And here's my errors:
H:\Java\Iteration.java:12: error: illegal start of expression
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
Any help, please?
You can't define a method inside another method. Close your main method first, then start RandomDataAnalyzer:
public static void main(String[] args) {
// Contents of main.
}
public int RandomDataAnalyzer(int Rando) {
// Contents of RandomDataAnalyzer.
}
I'm going to assume that this isn't a homework problem and that you're learning Java on your own. If I'm wrong, shame on me for giving a working version. But my impression is that you'll learn from this:
public class gpaCalc
{
static Random rand;
static int rando;
public static void main(String[] args)
{
ArrayList<Integer> NumList = new ArrayList<>(); // use ArrayList
for (int i=0;i<=100;i++)
{
rand = new Random();
rando = rand.nextInt(1001);
NumList.add(rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
rando = NumList.get(i); // get is "opposite" of put--get the value put into the list earlier
sum = sum + rando;
}
System.out.println(sum);
}
}
There doesn't seem to be a need for a separate method called randomDataAnalyzer.
Welcome to StackOverflow.
Let's begin with the first issue: randomDataAnalyzer is being defined inside main method. Which is wrong, you should be actually defining it at the same level.
Taken into consideration, you should also add the static word before this function because this method is part of the class, and not of the elements. It's not necessary to create a new element of the class 'Iteration' for using a simple method.
Last, but not least, you are looping through the arraylist incorrectly. You are not even calling it. As you will see now:
import java.util.*;
public class Iteration
{
public static void main(String[] args)
{
ArrayList<int> numberList = new ArrayList<int>(); // we define the arraylist
for (int i = 0; i < 100; i++)
{
numberList.add(new Random().nextInt(1001)); // we add a random number to the list
}
// finally, after the 100 values were added..
System.out.println(randomDataAnalyzer(numberList)); // we show the output
}
public static int randomDataAnalyzer(ArrayList<int> list) // we will send this function an arraylist which will get the Σ.
{
int sum = 0;
for (int value : list) // this is how we loop through foreach value in the list
{
sum += value; // which means sum = sum + value.
}
return sum; // after looping and summing up, here'll be the result
}
}
I hope this was what you were looking for.
Here's a working version. Note the changes to your original:
Don't define methods inside methods: it is illegal syntax.
Rando, NumList: the naming conventions are to start classes, interfaces, enums (i.e. types) with a capital letter, and methods, fields, and variables with a lowercase case letter;
Removed the int Rando parameter alltogether: it's value was never used (it was only assigned to)
Use the values from numList rather than generating new numbers.
Added a method illustrating that the use of such a list is not needed in this case; the 'list' of 1000 numbers is still present, but only conceptually.
import java.util.*;
public class Iteration {
public static void main (String [] args) {
int sum = new Iteration().randomDataAnalyzer();
System.out.println(sum);
}
private int randomDataAnalyzer() {
Random rand = new Random();
List<Integer> numList = new ArrayList<Integer>();
for ( int i=0; i<100; i++ )
{
numList.add( 1 + rand.nextInt(1000) );
}
int sum = 0;
for ( int i=0; i<numList.size(); i++ )
{
sum = sum + numList.get(i);
}
return sum;
}
// Note that the above method has the same effect as this one:
private int moreEfficient() {
Random rand = new Random();
int sum = 0;
for ( int i=0; i < 100; i++)
sum += 1 + rand.nextInt(1000);
return sum;
}
}

random string of numbers

I want to print a string of numbers, but I get the followyng: [I#7c230be4
This is my code:
import java.util.Random;
class Aleatorio {
public static void main(String[] args) {
Random diceRoller = new Random();
int cifra[]= new int[5];
for (int i = 0; i < cifra.length; i++) {
int roll = diceRoller.nextInt(9)+1 ;
cifra[i]=roll;
}
System.out.println(cifra);
}
}
You are seeing the Object#toString representation of the int array Object. To display its contents, you could use:
Arrays.toString(cifra)
Try this
for (int c : cifra) {
System.out.println(c);
}
instead of this
System.out.println(cifra);

Categories

Resources