Set value for all values in an array - java

So basically I have an Array and I want to use the same IF-statement for all values without having to copy-paste the IF-statement so many times. E.g.
if(NewArray[] < 10){
NewArray[] = NewArray + 1;
}
Is this in any way possible?
Thanks in advance.

You have to use a for loop. This code will solve your problem.
public static void main(String[] args) {
int newArray[] = new int[10];
for(int i = 0; i < newArray.length ; i ++){
newArray[i] = i;
}
/* DISPLAY YOUR ARRAY */
for(int integer : newArray){
System.out.println(integer);
}
}

Related

Issue trying to create a Bubble Sort using ArrayList<Integer>

Hi I'm trying to figure out how to use BubbleSort in Java and my code is erroring and I don't know why
import java.util.ArrayList;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = arr.size();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr.get(j) > arr.get(j+1))
{
int temp = arr.get(j);
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
When I get to arr.get(j) = arr.get(j+1); and arr.get(j+1) = temp; the left side errors saying "The left-hand side of an assignment must be a variable." can anyone help me fix this?
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
You're trying to assign a value to the result of a method call.
You just can't do this. You can only assign to a local variable, a field in the current class, a field access (e.g. foo.bar = ...) or an array element (e.g. foo[0] = ...).
Instead, you should use set to update a list element:
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);
For the specific case of swapping two elements around in a list, you can instead use Collections.swap:
Collections.swap(arr, j, j+1);
You are doing several things wrong.
The obivous get and set issues already mentioned.
The fact that your are sorting an empty list. You pass in nums but sort the one you create which is empty.
You should use a boolean to prevent unnecessary repeats of the outer loop. Think of it like this, if you don't make a swap on the first iteration of the outer loop, then you won't swap on subsequent iterations.
And one style suggestion. Don't use loops or if statements without {}. Even if they only contain a single line of code. You will be less likely to make coding errors if you do so.
Try the following:
public static void BubbleSort(List<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}

Populate an array within a specific range

I wanna populate an array with integers within 2000-3000.
public static void main(String[] args) {
int[] nums = new int[1000];
for (int y = 0; y < nums.length; y++) {
for (int i = 2000; i < 3000; i++) {
nums[y] = i;
}
}
System.out.println(Arrays.toString(nums));
}
I got an array with full of 2999.
What's the problem? Thank you in advance!
you're populating the same cell again and again. Your array size is 1000, but your range is 1001: 3000 - 2000 + 1 = 1001
public static void main(String[] args) {
int[] nums = new int[1001];
for(int y=0;y<nums.length;y++) {
nums[y]= y + 2000;
}
System.out.println(Arrays.toString(nums));
}
What about Java 8 solution?
IntStream.range(2000, 3001).toArray(); // [2000, 2001, ... 3000]
You dont need nested loop to do that just do
int[] nums = new int[1000];
for(int i=2000; i<3000; i++) {
nums[i-2000]=i;
}
System.out.println(Arrays.toString(nums));
you get 2999 because your loop ends i<3000 , just change it to i<=3000 and also increase the array length to
int[] nums = new int[1001];
DEMO
It helps if you can translate your code into human language.
Breaking down your code, you have two loops. One is:
int[] nums = new int[1000];
for (int y = 0; y < nums.length; y++) {
// Stuff
}
}
Your idea in the first loop is to iterate through the whole length of the array.
"For each index in the array..."
Then, you have another loop inside the array iterator:
for (int i = 2000; i < 3000; i++) {
nums[y] = i;
}
Here, you are trying to put a number from 2000 to 2999 into index y of the array.
"In index y of the array, put values 2000 to 2999."
The previous values are overwritten for every value you put. This ultimately ends up as:
"Put 2999 in index y of the array."
Putting them together:
"For each index y in the array, put 2999."
Check TDG's answer for the proper way of writing the code.
Another way with 1 loop.As mentioned by #silentprogrammer , you need to increase array size by 1.
public static void main(String[] args) {
int var=2000;
int[] nums = new int[1001];
for (int y = 0; y < nums.length; y++) {
nums[y]=var++;
}
System.out.println(Arrays.toString(nums));
}

Check an integer variable against integers already stored in an array

Disclaimer: Still very new to code and have only basic skills with java. Trying to learn as much as i can on my own and from others. Not currently studying at uni.
Hello everyone.
I am trying to create an array with a small capacity (5 integers) to store a randomly generated integer in each array element. The randomly generated integer is in a set range (0-75) which ive no issue with.
What i cant figure out how to do is how to Generate a new integer, then check it against the current existing integers in each array element, before storing it and moving on to the next.
What i tried was this:
public class ItemSet
{
public static void main(String []args)
{
int[] itemSet;
itemSet = new int[5];
itemSet[0] = 0; /* to initialise the array elements. Im not sure if i actually have to do this or not */
itemSet[1] = 0;
itemSet[2] = 0;
itemSet[3] = 0;
itemSet[4] = 0;
int count = 1;
int assignItem = 0;
int countTwo = 1;
while (count > 5) {
while (countTwo == 1) {
assignItem = (int)(Math.random()*76);
// here is where i get totally lost
if (assignItem.compareTo(itemSet)) {
countTwo = 1;
} else {
itemSet[(count--)] = assignItem;
countTwo = 0;
}
}
count = count++;
}
}
}
Ive been looking at this so long my head is starting to hurt. I'd appreciate any advice you can give me. :) Thank you in advance. xx
Edit: Couldnt find the solution i needed in any of the "how can i test if an array contains a certain value" type questions, because i need to be able to have the number randomise again before it stores itself in the array element if it does happen to be the same as another previously generated integer.
You are doing too much to just fill an array. To fill an array, try using a "for" loop like so:
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
}
}
}
To print the values stored in the array, try using an enhanced-for loop:
for (int element : itemSet) {
System.out.println(element);
}
To check the values BEFORE storing the next integer, (say to see ensure that the new stored value would be unique) you could use a nested for loop that starts at the value beneath the outer loop and walks backwards, comparing each value that came before to the value that was just stored, and if they are the same, it will decrement the outer counter which will then override the data on the next loop:
import java.util.Arrays; // you need this to use Arrays.toString()
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
for (int j = i - 1; j >= 0; j--) {
if (itemSet[j] == itemSet[i]) {
System.out.println("Comparing " + itemSet[j] +
" and " + itemSet[i]);
i--;
break; // not really needed but illustrates a way to exit a loop immediately
}
}
}
// this is a handy way to print all the data in an array quickly
System.out.println(Arrays.toString(itemSet));
}
}
public static void main (String[] args){
//you dont need to initialize the array with zeros
int[] itemSet = new int[5];
int counter = 0;
while(counter < itemSet.length){
int random = (int)(Math.random() * 76);
//checks if the array already contains the random number
if(!Arrays.asList(itemSet).contains(random)){
itemSet[counter] = random;
counter++;
}
}
//print the array
for(int i : itemSet) System.out.println(i);
}
There are many ways you could solve this problem, I would suggest using a helping method that looks for duplicates in your array. This would be a working example:
public static void main(String[] args) {
int[] itemSet;
itemSet = new int[5];
int assignItem;
for (int i = 0; i < 5; i++) {
assignItem = (int)(Math.random()*76);
if(!duplicate(assignItem,itemSet,i)){
itemSet[i] = assignItem;
}
}
}
private static boolean duplicate(int assignItem, int[] itemSet, int i) {
for (int j = 0; j < i; j++) {
if (assignItem == itemSet[j])
return true;
}
return false;
}
The most straight forward way would be checking through the array for existing value before inserting the current random value.
Generate a random value
Check if value exists in array
If already exist in array, generate another value
If not exist in array, set value to current element
In codes:
public static void main(String[] args){
int idx = 0;
int[] myArray = new int[5];
Random rnd = new Random();
int val = rnd.nextInt(76);
do{
if(numExistInArray(val, myArray))
val = rnd.nextInt(76); //if val exist in array, generate another number
else
myArray[idx++] = val; //if val not exist in array, fill array
}while(idx != myArray.length); //do not exit loop till all numbers are filled
}
public static boolean numExistInArray(int val, int[] array){
for(int x=0; x<array.length; x++)
if(array[x] == val)
return true;
return false;
}
I had a hard time understanding what youre asking for but ill give it a go anyway hoping this is what you want:
for (int count = 0; count < 5 ; count++) {
assignItem = (int)(Math.random()*76);
if (assignItem==itemSet[count]&&itemSet[count]!=0) {
//If true do this
}
else {
itemSet[count] = assignItem;
}
}
Checking if the generated number is equal to a position and if the position is empty (0) if its not equal (a new number) then it will assign value to your array.
If you know your set range (which is 0-75) and space isn't an issue, I would suggest maintaining a pool of unused integers. This would guarantee each value is unique, and would avoid iterating over your array of integers to check for duplicates:
public static void main(String[] args) {
List<Integer> unusedNumbers = new ArrayList();
// Populate list with values
for (int i = 0; i <= 75; i++) unusedNumbers.add(i);
int[] itemSet = new int[5];
for (int i = 0; i < 5; i++) {
int randomIndex = (int) (Math.random() * unusedNumbers.size());
int randomInt = unusedNumbers.remove(randomIndex);
itemSet[i] = randomInt;
}
}

How to store numbers in an array?

I just learned the array function in Java and now I wanted to store numbers from 1-19 in an array but don't know the right way to do it without the userinput function. Here is what I got, can you tell me if it is the right way to store number in array?
public class ArrayQuestion1 {
public static void main(String[] args) {
int a=0;
int array[] = new int [20];
for ( array[a]=1; array[a]<=19; array[a]++){
System.out.println(array[a]);
}
}
}
You would do something like this to fill your array with consecutive numbers from 0-19
public class ArrayQuestion1 {
public static void main(String[] args) {
int array[] = new int [20];
for (int a = 0; a < array.length; a++){
array[a] = a;
}
}
}
To store userinputs to int array you can do
int array[] = new int [20];
Scanner scanner=new Scanner(System.in);
for ( i=0; i<array.length; i++){
array[i]=scanner.nextInt();
}
If you want to store number from 0 to 19 you can do
int array[] = new int [20];
for ( i=0; i<array.length; i++){
array[i]=i;
}
public static void main(String[] args) {
int array[] = new int[20];
for (int i = 1; i < array.length; i++){
array[i] = i;
}
//To print all the elements in the array.
for(int j=1; i< array.length; j++){
system.out.println(array[j]);
}
}
You can insert into the array using the above method and can view the contents of array also.
If you want to add consecutive numbers you can use a simple for loop and to see them on the screen you can just iterate your array. That is all. Hope this can help you!
class Main {
public static void main(String[] args) {
int a=0;
int array[] = new int [20];
for(int i = 0 ; i < array.length ; i++){
array[i] = i;
}
for(int x : array){
System.out.println(x);
}
}
}
If you don't want user input for array , you have to store numbers manually in the array like ,
int a=0;
int array[] = new int [20];
for ( a=1;a<=19; a++){
array[a]=a;
}
above code will store 0 to 19 in your array . than you can use below for loop to print it
for ( a=1; a<=19; a++){
System.out.println(array[a]);
}
To use an array you have to declare it.
int array[] = new int [19];
If you want 19 numbers, then use an array with 19 elements.
Then you have to populate each number in the array. To obtain it, just use an index in your array:
array[index] = value
For example:
for ( int i=0; i<array.lenght; i++){
array[i] = xx;
}
Pay attention. The first index in your array is 0 (not 1)

Print all values in a 3d array

Is there a way to print all values in a 3d array?
This is what I got but getting a null pointer exception:
int i = 2;
int x = 15;
String[][][] arrays = new String[x][x][i];
String arraytext = "hello";
for (String[][] row: arrays)
Arrays.fill(row, arraytext);
for (int a = 0; a<=x; a++){
for (int b = 0; b<=x; b++){
for (int j = 0; j<=i; j++)
{System.out.println(arrays[a][b][j]);}
}
}
You have a problem filling your array. you are getting
java.lang.ArrayStoreException: java.lang.String at Arrays.fill(row, arraytext);
That is cause you are trying to add a String when is expected an String[][].
And for printing you can use Arrays.deepToString() is your answer.
System.out.println(Arrays.deepToString(arrays));
Example:
public static void main(String[] args) {
String[][][] array3d = new String[10][10][10];
for(String [] [] array2d : array3d){
for(String[] array : array2d){
Arrays.fill(array, "hello");
}
}
System.out.println(Arrays.deepToString(array3d));
}
The problem is that this:
for (String[][] row: arrays)
Arrays.fill(row, arraytext);
Is trying to pass row, which is a double array of strings, to a function expecting a single array of strings. To get the bottom level of your 3D array, you want this:
for (String[][] slice: arrays)
for (String[] row: slice)
Arrays.fill(row, arraytext);
You also have both issues addressed by other answers in your double loop: You'll get an index out of bounds unless you change the <=s to <, and sub isn't defined.
You're going out of bounds on your arrays, instead of <= try <.
for (int a = 0; a < x; a++){
for (int b = 0; b < x; sub++){
for (int j = 0; j < i; j++)
{System.out.println(arrays[a][b][j]);}
}
}
Also, what is sub? You're code snippet should show where you define this variable.
Looks like you are experiencing off by 1 error (use < instead of <=):
for (int a = 0; a<x; a++){
for (int b = 0; b<x; b++){
for (int j = 0; j<i; j++)
{System.out.println(arrays[a][b][j]);}
}
}
Since you declared arrays as
String[][][] arrays = new String[x][x][i];
the bounds are from 0 to x-1 for the first two indexes, and 0 to i-1 for the thrid index.
Also, you're incrementing unknown variable sub rather than b in your second loop
You just forgot to replace a temporary value from copy-pastaing
for (int a = 0; a<=x; a++){
for (int b = 0; b<=x; sub++){ // sub here <---
for (int j = 0; j<=i; j++) {
System.out.println(arrays[a][b][j]);
}
}
}
Also see #jh314 's answer, your doing the off by one error
package academy.learnprogramming;
import java.util.Arrays;
public class Print3DArray {
public static void main(String[] args) {
// declare & initialize an int 3D array firstInt3D
int[][][] firstInt3D = {
{{1,2}},
{{3,4}},
{{5,6,7,8},{9,10}},
{{11},{12,13,14}},
};
// print all values of firstInt3D page by page
int x = 0;
for (int[][] accessPage: firstInt3D){
System.out.println("page:" + x);
if (x < firstInt3D.length) x++;
for (int[] accessRow: accessPage){
System.out.println(Arrays.toString(accessRow));
}
System.out.println();
}
}
}

Categories

Resources