Just to keep my skills sharp, I decided to write a small programme that prints out the values of an array, after being given two variables that each contain a different value.
My expectation was that each value would show onscreen, but this did not happen. Instead, only the last element's value was displayed onscreen (in the code below, being the number "2" --> That is an integer, not a string).
Why is this?
Also, why does dynamic initialisation produce the result I wish, but not the way I do it in the code?
Many thanks.
int[] arrayOne;
arrayOne = new int[2];
int numOne = 1;`
int numTwo = 2;`
for (int i = 0; i < arrayOne.length; i++) {`
arrayOne[i] = numOne;
arrayOne[i] = numTwo;
System.out.println(arrayOne[i]);
}
If you want to put the values of two variables into an array, you need to use two assignments:
arrayOne[0] = numOne;
arrayTwo[1] = numTwo;
Now you can use a for loop to print out the contents of the array.
This kind of defeats the purpose of using an array, though.
You're setting different values to same location, causing only last value to be saved.
Your code similar to doing:
arrayOne[0] = 1;
arrayOne[0] = 2;
After these two lines, arrayOne[0] will hold the value of 2.
If you want to put these two values, you need to put them in different places:
arrayOne[0] = 1;
arrayOne[1] = 2;
In Java (and in almost any language I know), an array can only contain one vale per cell i.e. if you do "array[i] = 1" and after "array[i] = 2" , then the i-cell will CHANGE its value from 1 to 2, not append the value 2 after the 1. In the end, youre array will contain numTwo in every single cell.
If you want to initialize the array with a different value in each cell, I'm afraid you need to do it manually, not using the loop.
You need to do the population of your array before you iterate through it with the loop.
arrayOne[0] = numOne;
arrayOne[1] = numTwo;
Then do your loop:
for (int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
Many ways to initialize an array...
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
Or:
int[] a = new int[2];
for( int i = 0; i < a.length; i++ ){
a[i] = i + 1;
}
Or:
int[] a = new int[]{ 1, 2 };
Or.
int valOne = 1;
int valTwo = 2;
int[] a = new int[]{ valOne, valTwo };
Take care when you see more than one assignment to the same array element in a loop as you have it before the println. Is this what you want? The second one wins and sets the current (i-th) element to 2.
You need to do something like this:
public class demo{
private static int i = 0;
private static int[] demo = new int[10];
public static void main(String[] args){
for(int i = 0; i < 10; i++){
addElementToArray(i);
}
for(int i = 0; i < demo.length; i++){
System.out.println(demo[i]);
}
addElementToArray(i);
}
public static void addElementToArray(int input){
try{
demo[i] = input;
i++;
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
Don't set the values inside the for-loop either, that is (imo) plain stupid, for what you are trying to achieve
Related
Write a method sum(int[] values) that returns the sum of elements of the array values.
when I display my sum method it only displays the last element of the array
(I'm still a beginner, so go easy on me please)
System.out.print("Generated numbers for player 1 are: ");
int values1 = 0;
for (int i = 0; i <= 10; i++) {
values1 = 1+(int)(Math.random()*(6-1));
System.out.print(values1+" ");
}
System.out.print("\nGenerated numbers for player 2 are: ");
int values2 = 0;
for (int i = 0; i <= 10; i++) {
values2 = 1+(int)(Math.random()*(6-1));
System.out.print(values2+" ");
}
int[] player1 = {values1};
int[] player2 = {values2};
System.out.println("\n");
sumArray(player1);
sumArray(player2);
System.out.println(sumArray(player1));
}
public static int sumArray( int[] sum) {
int add=0;
for(int i=0; i< sum.length; i++) {
add += sum[i];
}
return add;
Main problem lies within your for loop. You are just updating values1 and values2 variable .You should be also adding them to the the arrays.
code will be
int[] player1 = new int[11];
for (int i = 0; i <= 10; i++) {
values1 = 1+(int)(Math.random()*(6-1));
player1[i] = values1;
System.out.print(values1+" ");
}
In addition you don't need these 2 lines.
int[] player1 = {values};
int[] player2 = {values2};
You are not understanding how to populate arrays
int[] player1 = new int[10];
for (int i = 0; i < 10; i++) {
values2 = 1+(int)(Math.random()*(6-1));
System.out.print(values2+" ");
player1[i] = values2;
}
I have changed the size of the array to be 10 and not as you have coded it (which result in entry of 11 elements)
Your player1 & player2 are only containing single element & that is reason you are getting sum as last element's (or single element's ) value.
If you want to have values1 containing multiple values then consider defining it as array instead of single integer.
int values1 = new int[11];
for (int i = 0; i <= 10; i++) {
values1[i] = 1+(int)(Math.random()*(6-1));
System.out.print(values1[i]+" ");
}
Similar case for your values2. After that, you can directly call:
sumArray(values1);
No need to define separate player1 & player2.
I would suggest a few things.
First, you should try not to "duplicate" the code. Here Player1 and Player2 could be just passed as parameters for a method that would generate their arrays.
Second, if you want to do any manipulations on arrays, you should avoid [] but instead use ArrayList for example.
Also, you may want to look into Object Oriented logic, as you don't seem to use class for Person, depending on what you want to achieve, you could use a class "Person" with attribute "values" which would be of type ArrayList.
As for your code, you reallocate "value1" and "value2", so they are just integers, not lists.
This would give something like this:
public static int generateValue(PersonClass person) {
ArrayList<Integer> values = new ArrayList<>();
for (int i = 0; i <= 10; i++) {
values.add(1+(int)(Math.random()*(6-1)));
}
person.setValues(values);
return sumArray(values);
}
public static int sumArray(ArrayList<Integer> values) {
int add=0;
for (Integer value : values) {
add += value;
}
return add;
}
This way, you will be able to retrieve your values and to print them as you want. The "PersonClass" part is not mandatory, it just depends if you want to keep your values associated to a Person or not (how long will you need those data).
(Example of class PersonClass :
public class PersonClass {
private ArrayList<Integer> values = new ArrayList<>();
public ArrayList<Integer> getValues() {
return this.values;
}
public void setValues(ArrayList<Integer> newValues) {
this.values = newValues;
}
}
as you should always use getters and setters). Good luck on you way to Java learning.
Okay, so I need to print 10 rows from 1 to 10 and 15 columns in every row from 1 to 15 with lines in between numbers. The second subroutine runs on its own, but only prints 0's and the first subroutine is me trying to give value to rows and columns, but I know I'm doing it very wrong. Any help is appreciated
static int ROWS = 10;
static int COLUMNS = 15;
static int[][] myArray = new int[10][15];
static int i; // loops through the number of rows
static int j; // loops through the number of columns
static int num1 = 0;
static int num2 = 0;
public static void vlueArray() {
for (i = 1; i < ROWS; i++) {
myArray[i][j]= num1++;
for (j = 1; j < COLUMNS; j++) {
myArray[i][j] = num2++;
System.out.print(myArray[i][j]);
}
System.out.println("");
}
}
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}
}
you have not initialized elements in array and that is why you are getting zero displayed because int values are always initialized by the compiler even if you don't initialize them. The default value of int is 0.
Initialize your 2D array like this:
int[][] myArray = new int[10][15]{{2,3},{3,5},..........};
Hope this helps.
There are two issues here. First, you don't have very good syntax, while the way you have this set up does work, let me give you a couple of tips about settings this up, and then we can fix your problem fairly easily.
Some general rules here:
You don't have to initialize loop variables in the class variables, just initialize them in the loop structure (I'll show you this below).
Use the ROW and COLUMN in declaring your array, it helps make sure the array length values are the same throughout.
Your loop for creating the values in vlueArray is incorrect. I'll show you some correct formatting for placing these values below.
When you array is initialized, each place in the array (if it is an integer array) is automatically given a value of zero. You can change this, but since the first method doesn't run correctly, printing the values in the array without changing them will give the array of zeros.
Now, it seems like you want to just have 1 - 15 on 10 different rows. To do this, you only need one variable, so my response code will only have one variable, but if this isn't what you want, I'd be glad to help you get a different setup.
So now that you have a little bit of background information, let's get you some working code.
static int ROWS = 10; //Your row count.
static int COLUMNS = 15; //Your column count.
static int num = 0; //Our number.
//Using the constants to make sure rows and columns values match everywhere.
static int[][] myArray = new int[ROWS][COLUMNS];
public static void fillArray() {
//Initializing the loop variables in the loop is the common practice.
//Also, since the first index is zero, the loop needs to start at 0, not 1.
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
//If you want 0 - 14, use `num++`.
//If you want 1-15, use `++num`.
myArray[i][j] = num++;
}
num = 0; //This sets num back to zero after cycling through a whole row.
}
//Your display method works just fine.
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}
I have to list out 10 unique numbers between 1 and 20, but before storing the numbers, the program should check whether the number is in the list or not. If the number is already in the list, it should generate a new number. Also, the amount of numbers replaced must be counted.
This is what I have so far:
public static void main(String[] args)
{
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
System.out.print("List: ");
for(int w = 0; w < arrayA.length; w++)
{
System.out.print(arrayA[w] + " ");
}
}
As you can see, there are two "3"s on the list, I have to output the same list but change one of the "3"s. Plus it has to be counted.
This is not hard to do, but what do you mean by change one of the threes?
You can add a boolean flag outside of your for loop that can tell if you've encountered a 3 or not and what the index of that 3 is.
Try something like this:
boolean changedThree = false;
int threeIndex = -1;
for(int i = 0; i < arrayA.length; i++){
if(arrayA[i] == 3 && !changedThree){
arrayA[i] = 4;
threeIndex = i;
changedThree = true;
}
System.out.println(arrayA[i] + " ");
}
I don't know for sure if that captures the information you need, but hopefully can give you a push in the right direction. Let me know if you have questions.
EDIT
To avoid any duplicate values, I recommend you create an array list, and add the unique values to it. Then, you can use the ArrayList.contains() method to see if a value exists already. So, I would recommend changing your code to this:
ArrayList<int> usedCharacters = new ArrayList<int>();
int changedCounter = 0;
Random rand = new Random();
for(int i = 0; i < arrayA.length; i++){
if(!usedCharacters.contains(arrayA[i])){ // If we haven't used this number yet
usedCharacters.add(arrayA[i]);
} else{
// Generate a new number - make sure we aren't creating a duplicate
int temp = rand.nextInt(20) + 1;
while(usedCharacters.contains(temp)){
temp = rand.nextInt(20) + 1;
}
// Assign new variable, increment counter
arrayA[i] = temp;
changedCounter++;
}
}
If you're not familiar with the random.nextInt() method, read this.
so if I understand you correctly you have to save the arrayA, right?
If that is the case, you can just make a new array, targetArray where you can save to numbers to, and then check using a for-loop if you already added it, and if so you can generate a new, random number.
The result would look something like this:
public static void main(String[] args) {
int[] arrayA = {16, 14, 20, 3, 6, 3, 9, 1, 11, 2};
int[] targetArray = new int[10];
int numbersReplaced = 0;
System.out.print("List: ");
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < targetArray.length; j++) {
if (arrayA[i] == targetArray[j]) {
targetArray[j] = (int)(Math.random() * 100);
numbersReplaced++;
} else {
targetArray[j] = arrayA[i];
}
}
}
System.out.println("Numbers replaced: " + numbersReplaced);
}
Hope that helped
You could use recursion to achieve your result.
This will keep looping until all values are unique
private void removeDoubles(int[] arr) {
for(int i = 0; i < arr.length; i++)
{
// iterate over the same list
for(int j = 0; j < arr.length; j++) {
// Now if both indexes are different, but the values are the same, you generate a new random and repeat the process
if(j != i && arr[i] == arr[j]) {
// Generate new random
arr[j] = random.nextInt(20);
// Repeat
removeDoubles(arr);
}
}
}
}
Note: This is the sort of question I prefer to give guidance answers rather than just paste in code.
You could walk the array backward looking at the preceding sublist. If it contain the current number you replace with a new one.
Get the sublist with something like Arrays.asList(array).subList(0, i) and then use .contains().
You logic for finding what number to add depends on lots of stuff, but at it simplest, you might need to walk the array once first to find the "available" numbers--and store them in a new list. Pull a new number from that list each time you need to replace.
EDIT: As suggested in the comments you can make use of Java Set here as well. See the Set docs.
I've read data from a text file and stored them in an array called 'boat1'.
There are nine values and I am trying to add together index's [4] to [9] to get a total value.
How would I go about doing this?
Here is my code:
String[] boat1 = new String[9];
int i = 0;
while(reader.hasNextLine() && i < boat1.length) {
boat1[i] = reader.nextLine();
i++;
}
I've tried to change the values to an integer but it doesn't seem to be working..?
Thank you.
You got to parse before adding:
int a = Integer.parseInt(boat1[3]);
int b = Integer.parseInt(boat1[8]);
int c = a + b;
Your array boat1 is a String array and not an int array. You need to convert it. Note that boat1 is size of 9 meaning that it has indexes from 0 to 8. Java is 0 based.
If you want to add up a sequence of numbers (ex. 3,4,...,7,8), just loop through the indexes you want to add up and keep track of a total.
Because your array is an String type it needs to be converted to int, After you do that you will have something like this example assuming that I'm making up those values , but it should still work for your code :). Don't forget to add the for loop at the end as I have it on my code so it can find the sum of your indexes. Hope it can help you!
int sum = 0;
int[] boat = new int[9];
boat[0] = 2;
boat[1] = 4;
boat[2] = 6;
boat[3] = 8;
boat[4] = 10;
boat[5] = 12;
boat[6] = 14;
boat[7] = 16;
boat[8] = 18;
for(int i = 3; i < boat.length ; i++){
sum += boat[i];
}
System.out.println(sum);
I have this method that doubles my initial array and then returns it as the new array. When I then reprint the new array, it doesn't show that it doubled. I will paste just the single method, but if it's not enough, let me know. It will print it correctly in the method when I use the second for loop, but when I call the method to print the array, it prints the initial array.
public static int [] doubleArray(int [] p)
{
int [] newArr = new int [p.length * 2];
for (int i = 0; i < p.length; i++)
{
newArr[i] = p[i];
}
p = newArr; //Here I set the new doubled array to equal the array in parameters
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
return p;
}
you're populating newArr only through length of p
When you set p = newArr, the array p is still going to keep its size, so its length will not double. You could try to return newArr instead of p, which should give you the doubled array you're looking for.
You are only iterating to p.length. You need to modify your logic to double the length in your first for loop while retaining the correct index to use.
It does doubles the length. Did you want the values to be copied too?
public static int [] doubleArray(int [] p)
{
int [] newArr = new int [p.length * 2];
for (int i = 0; i < p.length; i++)
{
newArr[i] = p[i];
newArr[2*i] = p[i]; //copy the value
}
p = newArr; //Here I set the new doubled array to equal the array in parameters
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
return p;
}
length extended.
try this...
public static void main(String[] args) {
int[] a = {1,2,4};
int[] s = doubleArray(a);
System.out.println(Arrays.toString(s));
}
it gives output [1, 2, 4, 0, 0, 0]
Arrays are objects and passed by reference. So if you expect that variable you passed to this method will change it's reference you are wrong.
I ran this code and its produces array of double length and at the beginning there are values of original array. As you use array of primitive type, empty places are populated with default values(0 for int)
Works fine for me. Are you sure you have the right reference for the returned value?
In any case have a look at System.arraycopy
public static void main (final String args[])
{
int [] p = {1,2,3,4,5,6,7,8,9};
final int [] newArr = new int [p.length * 2];
for (int i = 0; i < p.length; i++)
{
newArr[i] = p[i];
}
p = newArr; //Here I set the new doubled array to equal the array in parameters
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
}
Ok, #ZouZou solved the issue. When I called the method, I needed to set the initial array to equal the method. Thus when I returned the p array, it wrote it to the initial array.
ie;
initialArray = doubleArray(initialArray);
This works totally fine for me. I guess you have called the method in main like following:
public static void main (final String args[])
{
int [] p = {1,2,3,4,5,6,7,8,9};
doubleArray(p);
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
}
In the doubleArray method, you didn't extend the original array. But instead, you return a new one with extended size. So the changes will not reflect to the original array outside of the method.
To get the new one, you should catch the returned array and do printing with the new one.
Is this your actual question? Please clarify!
If yes: normally you can change the original array and make the changes reflects outside the method by changing the return type to void. Those changes could be changing elements' value. But you can't change an array's size once it is declared.