I'm very new to coding.
I'm writing this code and I'm struggling because I need to make a code that makes an array with 8 random integers and then it swaps the largest integer with the first number in the array.
When doing this though I'm getting an error and I cannot seem to fix it.
import java.util.Scanner;
import java.util.Random;
public class finalExam {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
Random spinner = new Random();
int [] userInputs = new int [8];
for (int i = 0; i < userInputs.length; i++) {
userInputs[i] = spinner.nextInt(100)+1;
System.out.println(userInputs[i]);
}
int largest = userInputs[0];
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest)
largest = userInputs[j];
}
System.out.println("Your largest number is: " + largest);
int holder;
int [] arr = new int[101];
for (int m = 0; m <= arr.length; m++) {
holder = largest;
userInputs[0] = userInputs[largest];
holder = userInputs[0];
}
}
}
The error comes from the last bit of your code. userInputs[largest] is out of bound because the array is only 8 integers long (while largest can have a value of 100).
Since you need the position of the largest number, you'll have to save it in largestPosition when you identify which number is the largest, like so:
int largest = userInputs[0];
int largestPosition = 0;
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest){
largest = userInputs[j];
largestPosition = j;
}
}
That said, the loop which you used at the end also isn't needed here. You could just swap the first value of the array with the largest one using this method:
int first = userInputs[0];
userInputs[0] = largest;
userInputs[largestPosition] = first;
Related
I am working on a selection sort algorithm and I'm running into a problem. Sometimes it sorts correctly, sometimes it doesn't. And I constantly run into the error "Index _ out of bounds for length _"
I'm completely stumped. Any advice? Work done in Java
public class Selection{
System.out.println("Please input a value for N");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] array = new int[n];
for (int i =0; i < n; i++) {
System.out.println("Please input a value for index" + i);
int element = input.nextInt();
array[i] = element;
}
select(array);
}
public static void select(int[] sorter) {
for (int i = 0; i< sorter.length; i++) {
int k = sorter[i];
int lowest_number = sorter[i + 1];
for (int j = i; j < sorter.length; j++) {
if (sorter[j] > -1){
lowest_number = j;
}
}
int intermediate = sorter[i];
sorter[i] = sorter[lowest_number};
sorter[lowest_number] = intermediate;
System.out.println("----------");
printarray(sorter);
}
}
public static void printarray(int[] print) {
for (int i = 0; i < [rint.length; i++) {
System.out.println(print[i]);
}
}
}
Your IndexOutOfBoundsException is caused by this code:
int lowest_number = sorter[i + 1];
which gets index i + 1 from sorter, which is one too much in case that i is sorter.length - 1.
Another issue is that lowest_number is being set to the last non-negative value index in sorter, rather than to the lowest value index.
This should give you a good indication on what to work on without giving away a full working insertion sort algorithm right away, as practise seems to be the goal here.
I am new to Java (and coding in general). I need to write a method that gets an integer, creates an array made of random numbers of the length of the integer, range 1-50
(inclusive) and finds the maximum and minimum number.
I was able to fill the array with random numbers. However, my min and max are not printing. I have been looking at this for hours with no luck - any advice would be very helpful! Thank you.
import java.util.Scanner;
import java.util.Random;
class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in .nextInt();
System.out.println();
int x;
int randNum;
int y;
//create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
} //for
} //for
} //main method
} //class
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
Look closely at this code. Inside the loop, you are setting
largest = array[s];
and then immediately checking
if (array[s] > largest)
Of course it's not, you just made them equal!
Put the assignments inside the conditions:
// Remove largest = array[s]
if (array[s] > largest) {
largest = array[s];
}
Similarly for smallest.
Note: I would recommend against commenting on closing braces. Note only is it unnecessary effort, it is confusion-prone: in this snippet of code above, the //for and //if are reversed. Additionally, it doesn't tell you which "if" or "for" it is closing.
Simply looking at the indentation is an easier way.
Your program does not fill the array with random numbers. It creates several arrays and fills each of them with a single number. You should change this part of the program:
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
/* min-max code */
}
}
to this:
Random r = new Random();
int[] array = new int[userNum];
for (int i = 0; i <= userNum; i++) {
array[i] = r.nextInt(50) + 1;
System.out.println(array[i]);
}
/* min-max code */
This will create a single array, fill it with random numbers, and print each element of the array, which seems to be what you intended.
The code that finds the minimum and maximum is also incorrect.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
} else if (array[s] < smallest) {
System.out.println(smallest);
}
}
You should only set largest or smallest when array[s] is actually the largest or smallest value in the array so far. To check whether or not this is the case, you can use Math.min() and Math.max(), which return the smallest or largest, respectively, of two values.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = Math.max(array[s], largest);
smallest = Math.min(array[s], smallest);
}
System.out.println(largest);
System.out.println(smallest);
This is what you looking for::
import java.util.Scanner;
import java.util.Random;
public class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in.nextInt();
System.out.println();
int x;
int randNum;
int y;
int[] array = new int[userNum];
// create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println("number " + i + ":: " + randNum);
array[i - 1] = randNum;
}
// print array
for (int s = 0; s < array.length; s++) {
System.out.println("array[" + s + "] number :: " + array[s]);
}
// find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
if (array[s] > largest) {
largest = array[s];
// find min
} else if (array[s] < smallest) {
smallest = array[s];
}
}
System.out.println("\nLargets Number:: " + largest);
System.out.println("Smallest Number:: " + smallest);
} // main method
} // class
Don't confuse too much when you are using loops.Some mistakes you done while writing code.
1> You have declared array int[] array = new int[userNum];
in for loop. which mean it will create as much arrays as loop iterate. and not accessible outside loop.
2> Same with variables largest and smallest int largest = array[0];
int smallest = array[0];
3> for (x = 1; x < 1; x++) control never ever enter the loop since your condition x<1 is never satisfy because you have initiated x=1 and and it will never ever be less than 1 as in condition (x<1).
Suggestion :: To find largest you have to traverse through array and check every element for largest and smallest and store it in separate variable rather than printing it at every check.
In my code i have used three for loops::
1>> to generate and print random number. In same loop i'm filling array with generated number.
2>> Here just printing array separately for better presentation in output.
3>> Finding largest and smallest by assigning values in if block if they satisfy condition.
I hope this will help you to understand code.
The problem is to find the minimum number in the random array 50 numbers. It should be between 0-100 and its index. I don't know what's the wrong with my code. It prints more than one minimum value and I haven't found a way to make limit to the array:
You are not generating random number properly.
To find a random number in range 0..99,use
Random r = new Random();
int randomInt = r.nextInt(100);
Try this
public class RandomTest {
public static void main(String[] args) {
int arr[] = new int[50];
Random r = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(100);
System.out.println(arr[i]);
}
int minimum = arr[0];
for (int j = 1; j < arr.length; j++) {
if (minimum > arr[j])
minimum = arr[j];
}
System.out.println("Minimum value-->" + minimum);
}
}
Output
Output will vary as per the generated number.In my case,I got
Minimum value-->4
You shouldn't print inside the "for" loop.
The loop determines which value is the minimum.
Once it has ended, print the result.
for{
...
...
}
System.out.println(Minimum);
You can use the following code:
int[] a = ...; // after random for
int min = a[0];
int minIndex = 0;
for(int i = 1; i < a.length(); i++) {
if(a[i] < min) {
min = a[i];
minIndex = i;
}
}
System.out.println(minIndex);
I had to write a program that find the largest element in an array. The user is prompted to enter the number of rows and columns, then prompted to enter the numbers in the rows and columns.
This array is then passed to a method where each number in every column of every row is compared and when the largest number is found the location is then moved to a field which, hopefully, return from the method.
It is not working. Here is my code.. I am sure that it is something silly, but what I can't figure it out. I think that it might have to with the 'a' in calling the method.
I define 'a' with double[][] a = new double[r][c];
I call and pass to the method with int[] find = locateLargest(a);
I tried to use all 3 of these as the return statement:
// return largest;
return largest[indxrow][indxcol];
// return [indxrow][indxcol];
How can I fix my code?
void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of rows and columns of the array");
int r = input.nextInt();
int c = input.nextInt();
double[][] rowCol = new double[r][c];
double[][] a = new double[r][c];
System.out.println("Enter the array");
for (int rows = 0; rows < rowCol.length; rows++) {
for (int cols = 0; cols < rowCol[rows].length; cols++) {
rowCol[rows][cols] = input.nextDouble();
a[rows][cols] = rowCol[rows][cols];
int[] find = locateLargest(a);
}
}
System.out.println("The location of the largest element is at (" + a[0] + ", " + a[1] + ")");
}
public static int[] locateLargest(double[][] a) {
double largest = 0;
int indxrow;
int indxcol;
for (int lcol = 0; lcol < a[0].length; lcol++ ) {
largest = a[0][lcol];
indxcol = lcol;
}
for (int lrow = 1; lrow < a.length; lrow++) {
for (int lcol = 0; lcol < a[lrow].length; lcol++)
if (a[lrow][lcol] > largest) {
largest = a[lrow][lcol];
indxrow = lrow;
}
}
// return largest;
return largest[indxrow][indxcol];
//return [indxrow][indxcol];
}
}
You are trying to return a double, when the actual return type of the method is an int[]
from how your code looks, it seems that you mean to return the largest number in the array.. In that case you should return a double, since your array you pass in is a double[][]
public static double locateLargest(double[][] a) {
double largest = 0;
for (int lcol = 0; lcol < a[0].length; lcol++) {
largest = a[0][lcol];
}
for (int lrow = 1; lrow < a.length; lrow++) {
for (int lcol = 0; lcol < a[lrow].length; lcol++)
if (a[lrow][lcol] > largest) {
largest = a[lrow][lcol];
}
}
return largest;
}
In order to return an int[] (as you specified in public static int[] locateLargest(double[][] a)) in your method, you should use
return a[lrow];
because a is an int[][], so a[a_certain_position] will be an int[], i.e. what you are looking for.
EDIT:
This assuming that a was an int[][], but I noticed you defined it as a double[][]. Keep in mind (int[])a[lrow] cast is not possible in Java, so I would suggest you to change your method to return a double[] instead, like this:
public static double[] locateLargest(double[][] a)
I looked at the code over and over but I can't seem to get rid of this error. What am I doing wrong? I'm getting an error at the line I bolded.
import java.util.Scanner;
import java.math.*;
public class HW1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// The numbers for n are not relevant
System.out.println("Please enter a number for the length of n.");
int n = input.nextInt();
// Creates an array with n values
int[] vectorArray = new int[n];
// Inputs random numbers into the array ranging from -100 to 100.
int dummy;
int temp = 0;
// Loop to generate negative and positive numbers into the array
for (int i = 0; i <= n; i++) {
dummy = (int)(Math.random()*2);
if (dummy == 0) {
temp = -1;
} else {
temp = 1;
}
**vectorArray[i] = ((int)(Math.random()*101)) * temp;**
System.out.println(vectorArray[i]); }
// Algorithm 1 - Brute force O(n^3)
int max = -1;
int sum;
}
}
}
You are accessing position n+1 in the array which is out of bounds.
Try changing the following line:
for (int i = 0; i <= n; i++)
To:
for (int i = 0; i < n; i++)
In general, I think its recommended to do something like this in case n ever changes after the array is initialized, and its more obvious what your code is doing (plus you'll never have to worry about this kind of Exception again):
for (int i = 0; i < vectorArray.length; i++)