This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
I am trying to find a way to print the contents of the array, while using a for loop. This is a fairly new section in java to me, as I am a beginner. Any help is appreciate in concerns to my question. My question is would I move the "Random" assessor method into the mutator method or am I just completely wrong and have to do something else.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray( ) {
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
}
}
My question is would I move the "Random" assessor method into the
mutator method or am I just completely wrong and have to do something
else.
You don't have to. Just use a loop to iterate through the array which is already filled in the constructor.
public void printArray( ) {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
System.out.println(arr[i]);
}
}
By the way, with Java 8, you can write less lines of code to achieve the same result:
Arrays.stream(arr).forEach(System.out::println);
public void printArray() {
//Print array
System.out.println(Arrays.toString(arr));
//another method with for loop
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i])
}
}
Note there is plenty of other techniques
In terms of writing clean code, it would probably be good to move this bit of code into its own private method within the class, and calling that within the constructor.
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
populateArray();
}
private void populateArray() {
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
Then in your printArray() method you can loop through the array and call System.out.println( ) for each item.
public void printArray( ) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
If you come from a more functional background, I can show you how to write this more functionally using Java 8 lambdas. Let me know.
Related
This question already has answers here:
What does java.lang.ArrayIndexOutOfBoundsException mean? [duplicate]
(7 answers)
Closed 4 years ago.
I am trying to return 4 characters to an array from a method but get the error shown below. I have tried to call the method in two positions so far and have commented them out below. What is the correct way to do this?
class App{
public static void main(String[]args){
App theApp = new App();
}
// position 1 - RandomizeCodeBlock();
char[] charactersAllowed;
char[] charArray;
public App(){
// position 2 - RandomizeCodeBlock();
for(int i=0; i<4; i++){
System.out.println(charArray[i]);
}
}
public char RandomizeCodeBlock()
{
char[] charactersAllowed = {'A','B','C','D','E','F','G'};
charArray = new char[4];
int i;
for(i = 0; i < charArray.length; i++) {
charArray[i] = charactersAllowed[(int) (Math.random() * 4)];
}return charArray[i];
}
}
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at App.RandomizeCodeBlock(App.java:33)
at App.<init>(App.java:17)
at App.main(App.java:5)
I'm not fully sure your code should do, but at least, the problem is in line {return charArray[i]
You get an error because at this moment i is 4, so it's out of the array scope.
This way it will at least work, but I'm not sure if it gives you expected result:
public class App{
public static void main(String[]args){
App theApp = new App();
}
public App(){
char[] currentCharacters = randomizeCodeBlock();
for(int i=0; i<4; i++){
System.out.println(currentCharacters[i]);
}
}
public char[] randomizeCodeBlock()
{
char[] charactersAllowed = {'A','B','C','D','E','F','G'};
charArray = new char[4];
int i;
for(i = 0; i < charArray.length; i++) {
charArray[i] = charactersAllowed[(int) (Math.random() * 4)];
}
return charArray;
}
}
What I changed: function randomizeCodeBlock() returns a randomized array.
Then the content of the array is printed to the standard output as you proposed.
Just in case you can use Java collections, please take a look at this article, to make sure that the Collection.shuffle method is not good for you.
This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 5 years ago.
I am trying to write an app that will set a fixed array of a any size and then pass that into the method as a parameter.
package com.company;
public class NumberManipulation {
double [] array = {500,250,-350,124,87};
double minimum = Double.MIN_VALUE;
double maximum = Double.MAX_VALUE;
public void getMaximum() {
for (int i = 0; i < array.length; i++) {
if (array[i] > minimum) {
minimum = array[i];
}
}
System.out.println(minimum);
}
public void getMinimum() {
for (int i = 0; i < array.length ; i++) {
if (array[i] < maximum){
maximum = array[i];
}
}
System.out.println(maximum);
}
}
package com.company;
public class Main extends NumberManipulation {
public static void main(String[] args) {
NumberManipulation number = new NumberManipulation();
number.getMaximum();
number.getMinimum();
}
}
I know that I can set an array to a fixed amount via:
double [] array = new double [10] //if I wanted the array to be 10 indexes
I can't figure out how to pass that into the getMin and getMax methods, though.
Just for the record, I was able to solve to the problem on my own. The recommendation provided with the link was not adequate for the answer. Here is a link it (https://gist.github.com/BrianARuff/4c49aee1a5644fee35e80b2547e6c74d)
I think you are searching something like this function
Arrays.copyOfRange(arr, i, j);
So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I tried a program where I take an integer array and randomise values in it. but I am not able to understand why but am getting a crazy output which displays special characters and all. what's wrong with my question. Here is my code:
import java.util.Random;
public class Q2d {
public static void shuffle(int[] arr) {
int n = arr.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
int temp = arr[i];
arr[i] = arr[change];
arr[change] = temp;
}
}
public static void main(String args[]) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
shuffle(arr);
System.out.println(arr);
}
}
You are attempting to print the array object. Arrays are objects too, but they don't override Object's toString() method, which is responsible for the "crazy output".
Use Arrays.toString():
System.out.println(Arrays.toString(arr));
I'm pretty sure you asked this question like 20 minutes ago and in it instead of
System.out.println(arr);
you had
for(int i:arr){
System.out.println(i);
}
which is correct...
I have a loop which assigns randomly generated integers into an array.
I need a way to ensure the same integer is not input into the array twice.
I figured creating a loop inside the overall loop would work but I am unsure on what to execute here.
int wwe[] = new int[9];
for(int i = 0; i < 9 ; i++){
int randomIndex = generator.nextInt(wwe.length);
wwe[i] = randomIndex;
System.out.println(wwe[i]);
System.out.println("########");
for(int j = 0; j < 9; j++){
System.out.println("This is the inner element " + wwe[j]);
}
}
If you want to enforce unique values, use a data structure meant for such a behavior, like a Set. TreeSet or HashSet would work perfectly.
You are actually looking for shuffling your array.
Note that what you really looking for is to find a random order of your array, this is called a permutation.
In java, it can be simply done using a list with Collections.shuffle().
If you are looking to implement it on your own - use fisher yates shuffle, it is fairly easy to implement.
Since other answers showed how to do it with Collections.shuffle() already - here is a simple implementation + example of fisher yates shuffle, that does not need to convert the original array into a list.
private static void swap (int[] arr, int i1, int i2) {
int temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
private static void shuffle(int[] arr, Random r) {
for (int i =0; i < arr.length; i++) {
int x = r.nextInt(arr.length - i) + i;
swap(arr,i,x);
}
}
public static void main(String... args) throws Exception {
int[] arr = new int[] {1 , 5, 6, 3, 0, 11,2,9 };
shuffle(arr, new Random());
System.out.println(Arrays.toString(arr));
}
Something similar to the following should meet your requirement.
It uses a HashSet to achieve unique elements.
Set<Integer> sint = new HashSet<>();
Random random = new Random();
while ( sint.size() < 9){
sint.add(random.nextInt());
}
For you example, you can use Collections.shuffle
public static void main(String[] args) {
List<Integer> a = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
a.add(i);
}
Collections.shuffle(a);
System.out.println(a);
}