Changing a variable outside a for loop from within the loop - java

In this situation an array nums has an undefined amount of integers in it and I'm trying to find the largest and print it. When I do this a is always printed as 0 because whatever is happening in the loop doesn't affect the a value outside of it. Anyone know how to fix this?
int a = 0;
for(int i=0;i>nums.length;i++){
if(nums[i]>a)
a=nums[i];
i++;}
System.out.print(a);

This code has two errors:
the loop will never execute since i will start with a value less than nums.length
you increment the loop index twice!
Your loop should look like this:
for(int i=0;i<nums.length;i++){
if(nums[i]>a)
a=nums[i];
}

Here is a solution for your problem:
import java.util.*;
class Main {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<Integer>();
Random r = new Random();
// Fill the ArrayList with integer RandomNumbers
int size = r.nextInt(100);
int maxValue = 0;
for(int i=0 ; i < size ; i++){
int value = r.nextInt(1000);
System.out.println("Current value: " + value);
arrayList.add(value);
if(value > maxValue)
maxValue = value;
}
System.out.println("Max: " + maxValue);
// If u want to shuffle the list
Collections.shuffle(arrayList);
}
}

Related

How do I increment every element in an array list by n elements?

I am only editing the bottom methods for this assignment. I am trying to increase every element of the list by n or "value" elements but I can't seem to figure out how. This is my approach so far. There is a method for finding the min not shown that works as intended. I am only trying to modify the body of the second method
public class ArrayListLab
{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(12);
list.add(45);
list.add(23);
list.add(48);
list.add(11);
System.out.println("Original list is " + list);
System.out.println("The smallest value is " + minimum(list)); // Expected: 11
modifyList(list, 5);
System.out.println("The new list is " + list);
}
public static void modifyList(List<Integer> list, int value)
{
for(int i = 0; i < value; i++);
list.get(i) += value;
}
I think you need to update your for loop to go from 0 to the length of list (for(int i = 0; i < list.size(); i++)) instead of go from 1 to value (for(int i = 0; i < value; i++)). You also need to remove the ; at the end of for statement so the Java program will take the list update code below instead of looping through an empty block of code.
Regarding how to update an ArrayList object, you can use the setfunction for that (list.set(i, list.get(i) + value))
public static void modifyList(List<Integer> list, int value) {
for(int i = 0; i < list.size(); i++)
list.set(i, list.get(i) + value);
}
Update: To rotate the ArrayList like you mention, you can remove and return the first element in the list using the function remove(0) and the just add it to end of the list using the add function like you did in the main function
public static void rotateList(List<Integer> list, int n) {
for(int i = 0; i < n; i++)
list.add(list.remove(0));
}
You should iterate over the list.
public static void modifyList(List<Integer> list, int value)
{
for(int i = 0; i < list.size(); i++){
list.set(i, list.get(i) + value);
}
}
In your code there are 2 errors
Logical
Syntax
Syntax for(int i = 0; i < value; i++); there's a ; and cause of that your variable i wont get recognized or say it would be out of scope.
Logical:
When you did list.get(i) all it does is, Gives you the value associated with that index.
You can do like int sum = list.get(i) + value what this will do it get the value from the list at index i and then add the number 5 to it. So now your sum holds value from index i + 5 which you wanted.
Now all you gotta do it set the index at i to the sum we calculated.
When we do list.set(i, sum) it overwrites the value at that index with our sum.
public static void modifyList(ArrayList<Integer> list, int value)
{
for(int i = 0 ; i < value ;i++) {
int sum = list.get(i) + value;
list.set(i,sum);
}
}
So you have a couple of problems, first in the method modifyList() the parameter List<Integer> should actually be ArrayList<Integer>. Furthermore, your for loop must have a { instead of ; at the end of the line.
An easier way to loop through ArrayLists is
for(Integer i : list) {list.set(i, i+value); }
Also, the minimum(list) is undefined.
Check out https://www.w3schools.com/java/java_arraylist.asp for help on arraylists

How to return the largest integer in an Array that has 10 random integers in it?

So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}

Random number from an array

I tried to generate a sorted list of random data with no duplicates in descending order for my array. It also returns number of duplicates, but it keeps printing out nothing but zero .... Can anyone help me please :(
// 2. Ask the user for size of arbitrary numbers.
System.out.print("Please enter a size for arbitray numbers: ");
int size = indata.nextInt();
int [] SortedNumbers = new int [size];
// 3. Process arbitrary numbers and remove all duplicates
int numDuplicates = generate_data(SortedNumbers);
// 4. Print the numbers and number of duplicates
printArray(SortedNumbers, numDuplicates);
and here is the random method
public static int generate_data (int [ ] list){
int duplicates = 0;
Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
return duplicates;
}
here is the print_array method
public static void printArray(int [] list, int duplicates) {
// Additional code required
System.out.println("\nSize of array: " + list.length + " .Numbers of duplicates: " + duplicates); for (int i = 0; i<list.length; i++){
System.out.printf("%7d", list[i]);
if ((i + 1) % 10 == 0){
System.out.println();
}
}
}
random.nextInt(n.length)
gives you a random index of your array.
But printing the value corresponding to this index, will always give you 0. As you never store any other value in the array.
You should rather do something like this :
int[] list = new int[10];
int duplicates = 0;
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int nextVal = random.nextInt(list.length);
System.out.println("list["+i+"] = "+ nextVal);
// test duplicates
for (int index = 0; index < i; index++) {
if (list[index] == nextVal) {
duplicates++;
break;
}
}
list[i] = nextVal;
}
return duplicates;
Your generate_data method always returns 0, since the local field duplicates is initialized with a 0 value and never changed.
The n field referenced by your generate_data method (which you haven't posted) is likely to be an int[], but its elements might not have been initialized (hence the print out will print default value 0, if within array index).
Hence your numDuplicates local field is always 0 too.
Notes
Your Random initialization is not performing. You should initialize a static Random object in your class and re-use it, instead of re-initializing every time in your generate_data method.
You probably want to have a look at coding conventions for Java in terms of field naming
You might want to post the code in your printArray method as well

how can i find the average of this?

I'm new to java programming and i just cant figure out how to find the average of an array nor do i know how to print the array backwards. This is my code so far:
public static void forwards(int nums, int arrayNums[]){
for(int a=0;a<arrayNums.length;a++){
nums =(int)(Math.random()*90+10);
System.out.print(nums+" ");
}
System.out.println();
System.out.println();
//Average of the array
int average=0;
for(int b=0;b<arrayNums.length; b++){
average=(average+arrayNums[b]);
}
System.out.println();
System.out.println(average);
}
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length; a>0;a--){
System.out.print(nums+" ");
}
}
public static void main (String [] args){
int[] arrayNums = new int [Integer.parseInt
(JOptionPane.showInputDialog("How many numbers do you want to input?"))];
int nums = 1;
forwards(nums,arrayNums);
System.out.println();
backwards(nums,arrayNums);
For average ---->
for (int i = 0; i < array.length; i++)
{
sum += array[i];
}
int avegare = sum / array.length;
For Backwards ---->
for(int i = Array.length - 1; i >= 0;i--)
Backwards should start with arrayNums.length-1:
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length-1; a >= 0; a--){
System.out.print(arrayNums[a]+" ");
}
}
The reason is that indices go from 0 to array.length-1. That's basically what happens in a for loop.
For the average, you forgot a division by the number of elements...
"i just cant figure out how to find the average of an array nor do i know how to print the array backwards."
For averages, you should use a different method, instead of trying to it in the forwards method
public static double average(int[] arrayNums) {
double sum = 0;
...
double average = // how do you get the average of something?
return average;
}
I started you off with the basic outline. You basically need to add all the numbers to the sum, by looping through the array, then get the average by diving it by the total of numbers in the array. Then you can print out the average like
double average = average(array);
System.out.println(average)
for backwards, you want to print arrayNums[a] instead of nums. You should also start the loop from arrayNum.length - 1 as there is no index in the array arrayNums.length so you would get an ArerayOutOfBounds exception. Also you want the 0th index, so you want to use >=
for(int a = arrayNums.length - 1; a >= 0 ;a--) {
// print arrayNums[a]
You seem to be doing the same wrong thing for forwards as you are in backwards. You want to print the arrays value for each index a, and not nums
I would also create the random array in a different method
public static int[] randomArray(int num) {
int[] random = new int[nums];
.... may array by looping
return random;
}
Then you the main you could just do
int[] array = randomArray(num);
forwards(array);
backwards(array);
double average = average(array);
System.out.println(average);
As you can see, I pass no nums to the methods. I think you should take tha parameter out of the method signatures. I see no use for them.
Here is a simple way to find the average. Just add up each of the elements, and then divide by the total number of elements in the array:
public static double average(int[] array)
{
int average =0;
for(int i =0; i< array.length; i++ )
{
average += array[i];
}
return average/array.length;
}
Here is a backwards method. Start at array.length-1, which is the last index. From there, iterate down i--, and then end when i is zero.
public static void printBackwards(int[] array)
{
for(int i =array.length-1; i>= 0; i--)
{
System.out.print(array[i] +" ");
}
}
When you call the methods, this is the syntax you should use:
double avg = average(arrayNums);
System.out.println(avg);
printBackwards(arrayNums);

Performing a for-loop on a retrieved array

Continuing on my attempt at an app and I'm stuck again on the very next object.
Last time I asked about my Performer.java object which receives an array of 5 integers.
This time I am trying to manipulate the data through my Calculations object.
(Please correct me if I am labelling the wrong things objects)
import java.util.List;
public class Calculations {
public static int performCalcs() {
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
for(int i=0 ; i<=arrayOne.size() ; i++) {
int sumTotal = 0;
return sumTotal;
}
}
}
I am literally stuck. I know it doesn't make any sense, but what I am trying to do is add up all the numbers in my array and also calculate the average of the numbers in my array.
I think I did the "i" correctly, and I was able to retrieve my array into arrayOne, but don't know how to implement the "i" and make it perform either addition or multiplication until i<=arrayOne.size.
Thanks guys!
for(int i=0 ; i<=arrayOne.size() ; i++){
int sumTotal = 0;
return sumTotal;
}
What you are doing in the above code, is that you are entering the loop, and after the first interation you return sumTotal (which will be 0)
This is what you want to do
int sumTotal = 0; // declare the variable you want to to summerize outside the loop. If you declare it inside the loop it will be garbage collected once the loop finishes and the variable is lost
for(int i=0 ; i<arrayOne.size() ; i++){
sumTotal+=arrayOne.get(i); // add the value that is at the current index each iteration
}
//After the loop, somTotal will have the total added value of the integers in the `List`. Now you can continue from here
You should move sumTotal outside the for loop. Otherwise the sumTotal variable is re-initialized every time.
You should loop till i < arrayOne.size(). O.w. you'll get an IndexOutOfBoundsException
You do retrieve the i-th number in this way: arrayOne.get(i)
Then compute the average value by dividing sumTotal for the number of values in the arrayOne list.
Here's the code:
import java.util.List;
public class Calculations {
public static int performCalcs() {
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
int sumTotal = 0;
// Sum the numbers in the array
// Repeat until i < arrayOne.size()
for (int i = 0; i < arrayOne.size(); i++) {
int num = arrayOne.get(i);
sumTotal += num;
}
// Check that the array is not empty.
// If it is not, compute the average, o.w. return 0.
double avg = arrayOne.isEmpty() ? .0 : (sumTotal / arrayOne.size());
System.out.println("average: " + avg);
return avg;
}
}
The best way is to use for-each loop:
int sumTotal = 0;
for(Integer val: arrayOne) {
sumTotal += val.intValue();
}
To sum all the numbers in any Iterable you need to do this:
//Declare the variable to hold the total outside the loop.
int total = 0;
//Loop over the integers to sum.
for (Integer i : integers)
{
//Add the current integer to the total.
total += i;
}
//The total will now equal the sum of all the integers.
System.out.println("Total: " + total);
System.out.println("Average: " + (total / integers.size()));
The two important bits that your code was missing are:
the total variable must be declared outside the loop else it is simple reinitialized with each iteration.
you need to add the integers values together.
I guess it should look like this
public class Calculations {
public static int performCalcs(){
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
for(int i=0 ; i<=arrayOne.size() ; i++){
int sumTotal += i;
}
return sumTotal;
}
}
The issue here is that you are using "return" inside your loop. The i++ part is fine. Use the return outside of the loop. All of the answers above show this.
If you use "return" in your loop, it will only iterate once.
Move int sumTotal = 0; out of the loop (above) and return ... also (below). Inside the loop put sumTotal += arrayOne[I]. You are learning the hard way, aren't you?
you should pull the sum init and the return out of your loop
public static int performCalcs(){
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
int sumTotal = 0;
for(int i=0 ; i < arrayOne.size(); i++){
return sumTotal += arrayOne.get(i);
}
return sumTotal;
}
Note how sumTotal is returned within the loop, meaning that on the very first time through the loop it returns the first value. You want it to say
import java.util.List;
public class Calculations {
public static int performCalcs(){
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
int sumTotal = 0;
for(int i=0 ; i<arrayOne.size() ; i++){
sumTotal+=arrayOne.get(i);
}
return sumTotal;
}
}
returns work in java (and most programming languages) that there can be many in a function, and the first one that it finds the function ends and returns whatevers after the return, for example
public double someFunction(int a){
if (a!=5){
return a;
}else{
return 12;
}
return 999; //this return is never used under any circumstances because the function has already returned, good IDEs won't even allow it
}
Two returns and it uses the first one it finds
Edit:
As Maroun Maroun correctly states the for loop should be
for(int i=0 ; i<arrayOne.size() ; i++){
not
for(int i=0 ; i<=arrayOne.size() ; i++){
This is because java array indexes start at 0, so an array with 5 entries will have indexes 0,1,2,3,4

Categories

Resources