Output elements of arrayi n Java [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
How to print [ ] in an array (Java)
(7 answers)
Closed last year.
I am struggling to properly output the elements of an array in java. I know I should use a for loop to print out the array, but I am not sure exactly where to start in order to make sure all the values are printed after the function call in main. Any advice would be appreciated. Thank you!
/*
1 creator shares with 3 friends
1 minute = 3 shares/ friend
what does it look like after 10 mins
*/
public int[] shares(int minutes, int people){
int[] array = new int [20];
for(int i = 1; i <= minutes; i++){
people += Math.pow(3, people);
array[i] = people;
}
return array;
}
public static void main(String args[]){
Prc test = new Prc();
System.out.println(test.shares(10, 1));
}

In arrays, you should start with zero.
The for loop could be something like this:
for(int i=0; i<myArray.length; i++){
System.out.println(myArray[i]);
}

Related

java.lang.ArrayIndexOutOfBoundsException: simple for loop printing an array [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have a simple for loop which prints the content of an integer array. It keeps throwing java.lang.ArrayIndexOutOfBoundsException exception. I have been scratching my head for couple of hours not knowing what is that I am doing wrong
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 10; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}
The ArrayIndexOutOfBoundsException is thrown because you try to access the 11th element in a 10 element array.
Arrays use zero-based indexing, which means that when you do nums[0] you are trying to access the first element of the Array. So:
int[] nums = {100,90,80,70,60,50,40,30,20,10};
System.out.println(nums[0]);
will print
100
As a result of this, when you do nums[10], you are trying to access the 11th element, which doesn't exist. To fix this, you can start on index 9 instead of 10, like:
for(int i = 9; i >= 0; i--){ // "i" starts with a value of 9, so it works
System.out.print(nums[i] + " ");
}
Arrays in most programming language are indexed from 0 by default, so that means the first element which is 100 has an index of 0, so u access it as nums[0]. So from this u can realize that the last element in ur array has an index of 9 which is nums[9] ==10.
ur getting this error because ur trying to access the element at the 10th index even though ur array has elements only upto 9th index i.e nums[0] = 100, nums[1] = 90 ..... nums [9] = 10.
just change the i to 9 like this and it will work like a charm
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 9; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}

How to print an 2d array of Char (JAVA) [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
I am trying to print out a gameBoard that has a "-" for each spot of the array: however every time I run this code I get this printed to the console:
[[C#2a139a55.
Any suggestions?
public class Game {
public static void main(String[] args){
char realBoard[][] = new char[7][7];
for (int i=0;i<7;i++){
for(int j=0;j<7;j++){
realBoard[i][j]='-';
}
}
System.out.print((realBoard));
}
}
realBoard is an array, an object, so you can't just print it like that. You will need to iterate over the elements again
for(char[] y: realBoard) {
for(char x: realBoard) {
System.out.print(x);
}
System.out.println();
}
Unless you need to use the array data of mark elsewhere, you would be better off just using print statements inside your loops.
for(int i = 0; i < 7; i++) {
for(int j = 0; j < 7; j++) {
//Print for each row
System.out.print("-");
}
//Move to next line
System.out.print("\n");
}
You can't print a 2D array like that. To print a 2D array in one line you can use:
System.out.println(Arrays.deepToString(realBoard));
Or in multiple lines:
for(char[] x: realBoard)
System.out.println(Arrays.toString(x));
Credits: Java - Best way to print 2D array?

Errors in Java Array [duplicate]

This question already has answers here:
Error message for arrays [duplicate]
(2 answers)
Closed 5 years ago.
I know that the problem lies in the command line, but I have tried every which way to find a way to solve it, but I have completely no idea how I can fix the array to not be zero. I am still really new to arrays and have looked everywhere in my textbook on how to do this, but the only example does not include arrays.
here is the error I am getting.
I am using Netbean
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at arraysize.Arraysize.main(Arraysize.java:20)
Here is my code as well
package arraysize;
public class Arraysize {
public static void main(String[] args) {
int[] array = new int[ 10 ];
for ( int counter = 0; counter < array.length; counter++)
array[counter] = Integer.parseInt(args[counter]);
System.out.printf("%s%8s\n", "Index", "Value");
for (int counter = 0; counter < array.length; counter++)
System.out.printf("%5d%8d\n", counter, array[counter]);
}
}
It is because your input args array length is less than length of array, in the moment you iterate to 10 in row
array[counter] = Integer.parseInt(args[counter]);
and in moment counter variable exceed args length you get exception, for solve this you need to
pass args array with 10 or more length. To checkargs array argument you may pass it's size to console:
public static void main(String[] args) {
System.out.printf("arguments array size is: %d", args.length);
//your code
}

How to create an array with both int and char [duplicate]

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 8 years ago.
I'm trying to create a single array that contains the numbers 1-9 and the characters A-F. The array should look like: 1 2 3 4 5 6 7 8 9 A B C D E F. I don't know how to set the array up and would appreciate any advice.
Try this following piece of code,This will work for you,However you must keep in mind that An array can contain only a single type of value as said by #MadProgrammer in comments
import java.util.*;
public class MyClass
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
char[] arr = new char[16];
/*taking input from the keyboard*/
for(int i = 0; i < 16; i++)
{
arr[i] = sc.next().charAt(0);
}
/*displaying the contents of the array*/
for(int i = 0; i < 16; i++)
{
System.out.println(arr[i] + ",");
}
}
}
In this code the numbers 0-9,which you are taking as input are still inserted as characters.

print an array in random order [duplicate]

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 6 years ago.
how to print an array in random order in java?
example:
int[] myArray = {5,4,3,2,1};
when printed, result should possibly be:
3 2 1 4 5
or
4 3 2 5 1
You should look at writing a Fisher-Yates shuffle. It's pretty easy to do, and efficient. Effectively you logically partition the array into a "shuffled" part and an "unshuffled part" - then repeatedly pick a random element from the unshuffled part and swap it with the first element from the unshuffled part, to make that part of the shuffled part.
Alternatively, create a List<Integer> instead and then use Collections.shuffle. It's unfortunate that there isn't an equivalent for arrays, but Java's type system doesn't do terribly well in terms of making either arrays or primitives generic :(
(I'm assuming you know how to do the printing side, and that it's the shuffling side which is the tricky bit for you.)
Create a new array order = {0, 1, 2, 3, 4} and shuffle it. Then something like
for (int i: order)
System.out.print(myArray[i]);
Swap between random elements of array:
import java.util.Random;
public class JavaTest {
public static void main(String[] args) {
int[] myArray = {5,4,3,2,1};
Random random = new Random();
for (int i=0; i<20; i++) { // 20: is custom number
int i1 = random.nextInt(myArray.length);
int i2 = random.nextInt(myArray.length);
int tmp = myArray[i1];
myArray[i1] = myArray[i2];
myArray[i2] = tmp;
}
for (int i=0; i<myArray.length; i++)
System.out.print(myArray[i]);
}
}
create an instance of the random class and then use the integer i which will be the index. where it lands, compute before element and after element length and then do the same recursively.
int main(){
int array[10]={1,2,3,4,5,6,7,8,9,10};
int i,k,temp;
struct timespec spec;
long ms; // Milliseconds
/* pick a random number from 0 to 9 elements */
for (i = 9;i>0;i--){
clock_gettime(CLOCK_REALTIME, &spec);
ms = spec.tv_nsec / 1.0e6;
srand((int )ms);
temp = rand();
temp = temp % i;
printf(" %d \t ",array[temp]);
k = array[i];
array[i] = array[temp];
array[temp] = k;
}
printf(" %d \t \n ",array[0]);
return 0;
}

Categories

Resources