How to call an ArrayList - java

I'm trying to append all of numbers that the program generates, into an array.
I used ArrayList method. However i can't manage program to read arr elements.
import java.util.Random;
import java.util.ArrayList;
public class Numbers {
public ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
Furthermore; i'm trying all generated numbers to be read via another method.
(That part is the following)
How can the program read all generated numbers?
double [] numbers= StdIn.getNumbers(); // Stuck at here.
Is it possible to calling getNumbers method like that?

You can read it directly by creating the array list of type double:
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
public class Numbers {
public ArrayList<Double> getNumbers() {
Random getNum = new Random();
ArrayList<Double> arr = new ArrayList<Double>(1000);
int size = 1000;
for (int i = 0; i < size; i++) {
double gauss = getNum.nextGaussian() * 15 + 70;
arr.add(gauss);
}
return arr;
}
public static void main(String[] args) {
Numbers number = new Numbers();
ArrayList<Double> arr = number.getNumbers();
System.out.println(arr);
}
}

You can call from other class as bellow
import java.util.Random;
import java.util.ArrayList;
public class PrintArray {
public static void main(String args[]){
ArrayList<Double> arrelements=OtherClass.getNumbers();
java.util.Iterator<Double> iterator = arrelements.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
class OtherClass{
public static ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
You can iterate through the ArrayList to read numbers from your ArrayList.
import java.util.Random;
import java.util.ArrayList;
import javax.swing.text.html.HTMLDocument.Iterator;
public class PrintArray {
public static void main(String args[]){
ArrayList<Double> arrelements=getNumbers();
java.util.Iterator<Double> iterator = arrelements.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public static ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}

You might think of something like that:
Initiate on object of your class and call the function
public class Numbers {
public ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
return arr;
}
public static void main(String[] args) {
Numbers n = new Numbers();
List<Double> numbers = n.getNumbers();
for (Double number : numbers) {
System.out.println(number);
}
}
}

Numbers class
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public final class Numbers {
private Numbers() {}
public static List<Double> getArrayListOfNumbers() { // ArrayList
List<Double> numbers = new ArrayList<>();
for(double d : getArrayOfNumbers()) {
numbers.add(d);
}
return numbers;
}
public static double[] getArrayOfNumbers() { // Array
Random random = new Random();
double[] numbers = new double[1000];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextGaussian() * 15 + 70;
}
return numbers;
}
}
Test Drive:
import java.util.List;
public class TestDrive {
public static void main(String[] args) {
// Printing arrayList numbers
List<Double> arrayListOfNumbers = Numbers.getArrayListOfNumbers();
arrayListOfNumbers.stream().forEach(System.out::println);
// Printing certain arrayList object
System.out.println("\nArrayList #7: " + arrayListOfNumbers.get(7));
}
}
Extra info:
Usually when there's need for fixed size/length (total values/objects), arrays are used (in your case it's 1000).
While ArrayList is a collection implementing interface List, which is used when there's no need for fixed size/length or when there's need for size/length flexibility.

Related

How to apply a method from my main file in my JUnit test?

Our assignment says we should "write the source code and test code for a function named sumArray that accepts an array of ints and returns the sum of all elements from the array".
I think I've got SumArray.java to return sum OK, but I'm struggling to apply my method to the test input. Any help please? TIA.
SumArray.java
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
SumArrayTest.java
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
/**
* Test of main method, of class SumArray.
*/
#Test
public void testMain() {
System.out.println("main");
String[] args = null;
SumArray.main(args);
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
// int testResult = sumArray({2, 3, 4});
int testResult = SumArray sumArray(intArray);
assertEquals(expectedResult, testResult);
// fail("The test case is a prototype.");
}
}
Edit: I've tried to implement what's been suggested so far with some changes; really not sure of any of this is right; a lot of it is guesswork TBH.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray;
public static int sumArray(int[] arr) {
return sum;
}
public static SumArray input() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return new SumArray();
}
public static void main(String[] args) {
SumArray result = input();
System.out.println(result.sumArray(SumArray));
}
}
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
#Test
public void testSumArray() {
System.out.println("main");
String[] args = null;
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
assertEquals(expectedResult, SumArray.sumArray(intArray));
// fail("The test case is a prototype.");
}
}
The only error I'm seeing currently is 'cannot find symbol' for SumArray in main.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
The above is the original code you posted. Now, you say you get the correct output. Yes, here you do:
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray(); // this one will return the correct answer
sumArray(); // this one will not
}
}
The second one will return wrong data, because you don't reset the value of sum.
You should split the tasks: sumArray should receive an array, and should return the sum of the elements. Either you should change the name of the method, or change the implementation, that is what Mahmoud told you.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static Scanner scan = new Scanner(System.in); // create this on class level, not every execution of your method
public static int[] buildArray(int elements) {
int[] arr = new int[elements];
for ( int i = 0; i < elements; i++ ) {
System.out.println("Enter element nr: " + (i+1));
arr[i] = scan.nextInt();
}
return arr;
}
public static int sumArray(int[] input) {
int sum = 0; // don't use a class level one. especially not a static one, it's value could be altered by another thread
for ( int in : input ) { // iterate over the array and add the values
sum += in; // this should be in -> each iteration we add the value of in (the element of the array) to sum
}
return sum;
}
public static void main(String[] args) {
System.out.println("Provide the size of the array: ");
int param = scan.nextInt();
int[] array = buildArray(param);
int result = sumArray(array);
System.out.println("The sum of the array is: " + result);
}
}
This approach will land you with far lesser issues. It also doesn't have static variables like n and sum in your class that might lead to wrong results.
The main() method is the entry point into the application, you shouldn't test the main() method. Instead, you should test the sumArray() method and compare the expected Vs. the actual returned value from the method.
As a side note, you can better pass the input array to the sumArray() method as a parameter instead of reading it from System.in within the method body.
So your method signature can look like this:
public static int sumArray(int[] arr). The client code which uses this method, which is the main method in your case (or the unit test) can pass the array without bothering the method how this input array was got.

Rounding off an arraylist to an integer array

I've been trying with this problem but couldn't wrap my head around it..
"Create a java method int [] roundoff (ArrayList input) that returns a new integer array containing all the input doubles correctly rounded off to integers."
This is where I got so far:
package javaProblem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class TowMethods {
public static int[] roundOff(ArrayList<Double> input) {
int [] iL=new int[input.size()];
for (double i:iL) {
//input.get(i);
int n=(int) Math.round(i) ;
iL[n]=n;
}
System.out.print(Arrays.toString(iL));
return (iL);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Double> input1 = new ArrayList<Double>();
input1.add(2.3);
input1.add(1.3);
input1.add(3.35);
/* for (int i = 0; i < 3; i++) {
double num = keyboard.nextDouble();
input.add(num);
}*/
int[] iList = roundOff(input1);
System.out.println(Arrays.toString(iList));
}
}
for (int i = 0; i < input.size(); i++) {
iL[i] = (int)(Math.round(input.get(i)));
}
Instead of your loop in roundOff method
Please try to use meaningful names when you name your variables. Also inside the roundOff method instead of the foreach loop use a classic for loop and don't iterate through the freshly created integer array but over the ArrayList which you take as a parameter.
Here is the possible solution:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class TowMethods {
public static int[] roundOff(ArrayList<Double> inputs) {
int [] integers=new int[inputs.size()];
for (int i=0; i < inputs.size(); i++) {
integers[i] = (int) Math.round(inputs.get(i));
}
return integers;
}
public static void main(String[] args) {
// Scanner keyboard = new Scanner(System.in);
ArrayList<Double> inputs = new ArrayList<Double>();
inputs.add(2.3);
inputs.add(1.3);
inputs.add(3.35);
/*
for (int i = 0; i < 3; i++) {
double num = keyboard.nextDouble();
inputs.add(num);
}
*/
int[] iList = roundOff(inputs);
System.out.println(Arrays.toString(iList));
}
}
If you want to take the user input just uncomment the commented lines in the main method.
Use Math.rint() which properly rounds to the next int value.
double [] dbls = {2.4, 8.8, 22.23, 97.6};
int[] ints = new int[dbls.length];
for (int i = 0; i < dbls.length; i++) {
ints[i] = (int)Math.rint(dbls[i]);
}
System.out.println(Arrays.toString(dbls));
System.out.println(Arrays.toString(ints));
Prints
[2.4, 8.8, 22.23, 97.6]
[2, 9, 22, 98]

I'm trying to make a java array code

i'm trying to build a code for different actions in arrays with different methods (Constructors) but i cannot seem to find a way to link them...I've made a array with 100 elements and a random variable to fill it....i'd like to know how to get my random elements from the first methods to the second one to make the comparing.... and also i'd like to not include in the 0 element in the random generator..any help?
this is my code
import java.util.*;
public class prova1{
public int min;
public void tabele(){
Random r = new Random();
int d;
int e[]= new int[100];
for(int i=0; i<e.length;i++){
d=r.nextInt(100);
e[i]=d;
System.out.println(e[i]);
}
}
public void emin(){
Random r = new Random();
int d;
int e[]=new int[100];
for(int i=0; i<e.length;i++){
d=r.nextInt(100);
e[i]=d;
if(e[i]<min){
min=e[i];
}
}
System.out.println("Vlera me e vogel eshte: " +min);
}
public static void main(String []args){
prova1 prova = new prova1();
prova.tabele();
prova.emin();
}
}
Return the array from tabele to a local variable and send it as parameter to emin
import java.util.*;
public class prova1 {
public int min;
public int[] tabele() {
Random r = new Random();
int d;
int e[]= new int[100];
for(int i=0; i<e.length;i++){
d=r.nextInt(99) + 1;
e[i]=d;
System.out.println(e[i]);
}
return e;
}
public void emin(int[] e) {
Random r = new Random();
int d;
for(int i=0; i<e.length;i++) {
if(e[i]<min) {
min=e[i];
}
}
System.out.println("Vlera me e vogel eshte: " +min);
}
public static void main(String []args){
prova1 prova = new prova1();
int[] arr = prova.tabele();
prova.emin(arr);
}
}

Displaying a shuffled integer array in java

sorry I'm really new to all of this. I know this is a stupid/easy question, but how would I display the shuffled array after i've set it all up. I have my code below and made the class that creates the array and has the algorithm for shuffling the integers inside the array. But I can't figure out how to display the shuffled array. Heres my code below:
My main:
package lab4b;
import java.util.Scanner;
public class Lab4B {
public static void main(String[] args) {
Shuffler test = new Shuffler(15);
test.Shuffle();
test.display();
}
}
and my Shuffle class:
package lab4b;
import java.security.SecureRandom;
public class Shuffler {
private static final SecureRandom randomNumbers = new SecureRandom();
private int [] data;
public Shuffler (int size){
data = new int [size];
for(int i = 0; i<data.length;i++){
data[i]= i+1;
}
}
public void Shuffle(){
int temp;
for(int first = 0; first<data.length; first++){
int second = randomNumbers.nextInt(data.length);
temp = data[first];
data[first] = data[second];
data[second] = temp;
}
}
public void display()
{
for(int counter =0; counter<data.length; counter++ ){
System.out.print(data[counter]+ " ");
}
System.out.println();
}
}
In this loop you are reset the value of the dataarray
for(int counter =0; counter<data.length; counter++ ){
// data[counter] = counter + 1; - do not do this
System.out.print(data[counter]+ " ");
}

Issues with adding a random numbers to an array

I am trying to add random numbers to an empty array 20 numbers 0-99. When I run the code below it prints out 51 numbers and they are all 0.
Can someone please help me figure out what I am doing wrong here.
import java.util.Random;
public class SortedArray
{
int randomValues;
int[] value;
public SortedArray()
{
}
public int getRandom()
{
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues = random.nextInt(100);
}
return randomValues;
}
public int getArray()
{
int result = 0;
value = new int[randomValues];
for(int item : value)
{
System.out.println("The array contains " + item);
}
return result;
}
}
Here is my main method
public class ReturnSortedArray
{
public static void main(String[] args)
{
SortedArray newArray = new SortedArray();
int random = newArray.getRandom();
int array = newArray.getArray();
System.out.println(array);
}
}
In your method getArray
the code
value = new int[randomValues];
is simply creating a new empty int array of size ramdomValues.
As the default value of an int is 0, that is what you are getting
Also in your method getRandom you are setting the same value time and time again
for (...)
randomValues = random.nextInt(100);
try
public int[] getRandomArr()
{
int randomValues [] = new int [20];
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues[j] = random.nextInt(100);
}
return randomValues;
}
I see a few issues, you should probably set the values in your constructor. You could also call it a set method (since it's not actually a get). Also, your getArray() doesn't return an array. So, I think you really wanted something like this,
public class SortedArray {
private Random random = new Random();
private int[] value = new int[20];
public SortedArray() {
super();
setRandomValues();
}
public void setRandomValues() {
for (int j = 0; j < value.length; j++) {
value[j] = random.nextInt(100);
}
}
public int[] getArray() {
return value;
}
}
And then your main method, should be updated like
public static void main(String[] args) {
SortedArray newArray = new SortedArray();
int[] array = newArray.getArray();
System.out.println(Arrays.toString(array));
}

Categories