Populate ArrayList with Random numbers then Print Array - java

I want to populate an arrayList with random numbers then print array. However I get a huge number of errors when executing the program. Any help would be appreciated.
public class methods {
//variables
int capacity;
private static ArrayList<Double> randomArray;
public methods(int capacity) {
//default constructor to initalize variables and call populateArray to
//populate ArrayList with random numbers
randomArray = new ArrayList<>(capacity);
populateArray();
}
//Method that populates Array with random numbers
private void populateArray()
{
Random rand = new Random();
for (int i=0; i<= capacity; i++)
{
double r = rand.nextInt() % 256;
randomArray.add(i,r);
}
}
//Get Array adds numbers to the string that is called in my main class and printed
public String getArray() {
String result = "";
for (int i=0; i<= capacity; i++)
{
result += String.format("%4d", randomArray);
}
return result;
}
}
//main
public class Benchmarking {
public static void main (String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("What is the capacity of your Array?");
int capacity = scanner.nextInt();
methods array1 = new methods(capacity);
System.out.println(array1.getArray());
}
After I run the program and enter the capacity it crashes. I just need to create an arrayList populate it with random numbers and print it. Here are the list of Errors I am receiving:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.util.ArrayList
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
at java.util.Formatter.format(Formatter.java:2520)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2927)
at Benchmarking.methods.getArray(methods.java:68)
at Benchmarking.Benchmarking.main(Benchmarking.java:27)
I think I am doing something fundamentally wrong with my methods.

You cannot pass randomArray (which is a java.util.ArrayList) to String.format().
You probably want to pass randomArray.get(i) instead.

Add this.capacity = capacity; into public methods() { constructor to start with. You are referencing this variable but never setting it.

Related

Can't use toString to display array

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

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

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

string array; java.lang.ArrayIndexOutOfBoundsException: 10

I have two classes that basically function as the most simplest database, where the user is supposed to enter a string and the program adds it in the array using a class that holds all the methods. Except that when i enter the first name it gives me java.lang.ArrayIndexOutOfBoundsException: 0. I know this means that no memory is being allocated for the array but i thought i did this in my second class where there is a constructer that defines the size of the array. Im not experienced enough with arrays to fix this debug on my own. Much help would be appreicated!
import java.util.*;
public class TestDatabase {
//contant value for data base 'size' of array
public static final int constant = 10;
public static void main (String[] args){
//Database object sets the array size to constant value
Database get = new Database(constant);
//input stream
Scanner in = new Scanner (System.in);
//varaibles for the count and index; prompt
int count = 0;
int index = 0;
System.out.println("Please enter 10 names to add them to the database. Name: " + (count += 1));
//while the count is lower than or equal to 10...
while(count<=10){
//input stream equal to input
String input = in.nextLine();
//if the count equals, stop the loop
if (count == 10)
{
//breaks the loop
break;
}
//prints out the current name
System.out.print(" Name: " + (count +=1));
//adds the input to the array
get.add(index,input);
//increments index by 1
index++;
}
//prints the array
get.print();
}
}
Here is my class with my all my methods:
import java.util.*;
public class Database{
//size of array
public int _size;
//array which has a varaible size
String[] userArray = new String[_size];
//contructer for the array size
public Database(int size){
_size = size;
}
//add method which adds a value to an index of an array
public void add(int index, String name){
//the values of string is placed into some index of the array
userArray[index] = name;
}
//print method which prints the contents of the array
public void print(){
//prints array
System.out.println(Arrays.toString(userArray));
}
//sort method which sorts the array
public void sort(){
//sorts the array
Arrays.sort(userArray);
}
//find method which finds a particular string in any index
public void find(String value){
Arrays.asList(userArray).contains(value);
}
}
Your ArrayList is never instantiated properly, you need to move it into your constructor so when the new operator is called, then the arraylist is created with the size variable that is passed, so something like this:
public Database {
private String[] data;
public Database(int size){
this.data = new String[size];
}
}
With your current code, the array is created before the size is actually given, so it defaults to a size of 0.
userArray init with zero length before your constuctor set _size. Create userArray in constructor.
there next steps performed when you create class:
_size init with 0
userArray init with zero length array
_size init with size value.
Change the code as below
String[] userArray;
public Database(int size){
_size = size;
userArray = new String[_size];
}

Initialize array when used in function?

I have a problem with this code.
the function setListSize is used to set the size of an array via user input as long as it's in the range of [1-50].
The code in the function works when not in a function but when I put the code inside the function I keep getting asked to initialize listA.
Tried to do
int [] listA = null;
but then I got Null Pointer Exception error.
int [] listA;
setListSize(listA);
public static void setListSize (int [] list) {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
list = new int [listSize];
break;
}
}
}
What can I do to make this work please?
Thank you for reading
You don't want to pass in the Array (note that it is an Array not a List, they are different things):
public void setListSize () {
You want to set up your member array:
listA = new int [listSize];
Before you were passing an array into the function then overwriting the reference to that array local to the function only. What you need to do is modify the reference to the array in the main object, for which either listA needs to be static (so the static method can access it) or setListSize needs to be non-static.
To make this function generic do this:
public static int[] createList() {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
return new int [listSize];
}
}
}
Then in your calling function just do:
listA = createList();
listB = createList();
etc.
You need to make the array static, and NOT pass it in to the function. Passing it in does indeed create the array, but it only exists during the lifetime of the function. This works:
import java.util.Scanner;
public class SetListSize {
private static int [] listA;
public static final void main(String[] igno_red) {
SetListSize.setListSize();
for(int i : listA) {
System.out.println(i);
}
}
public static void setListSize () {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
//Reference the array statically
SetListSize.listA = new int [listSize];
break;
}
}
}
}
Output:
[C:\]java SetListSize
Enter array size for between [1-50]: 12
0
0
0
0
0
0
0
0
0
0
0
0
public static int[] setListSize () {
...
return new int[listSize];
The problem is that passing a variable to a function will not be able to assign to that variable; in fact you are passing the value null. And have in the function a local variable list initialized with null.
You should understand what Java does inside.
When you have a method(int[] array)
And you assign something to the variable: array = new int[size], Java creates a new array and points the variable 'array' to the new array.
So if you want to assign a value a field outside the method, you should just do it. Call listA directly and assign a value to it.

Categories

Resources