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++)
Related
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;
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 trying to develop a program to delete all the median values from an array (the middle value if it has an odd number of elements, the two middle values if it has an even number of elements) until there are only two elements left, elements [0] and [1]. For example, if the user inputs 1, 2, 3, 4, 5, the program will return [1, 5]. I put down what I thought logically might help, but my array x isn't copying myArray in the for loops. I am not looking for someone to completely do the code for me, just to point out where I am wrong. Here is my code:
import java.util.*;
public class Deletion
{
public static void main(String[]args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the array length:");
int [] myArray = new int[kb.nextInt()];
int [] x = new int[myArray.length - 1];
int index1 = 0;
int index2 = 0;
int index3 = 0;
if(myArray.length < 3)
{
System.out.println("Please make sure array length is greater than two. Run again.");
System.exit(0);
}
else
{
for(int i = 0; i < myArray.length; i++)
{
System.out.println("Please enter a number for position " + i + ":");
myArray[i] = kb.nextInt();
}
for(int i = 0; i < myArray.length; i++)
{
while(myArray.length > 2)
{
if(myArray.length%2 != 0)
{
index1 = (myArray.length/2);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index1)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
else
{
index2 = (myArray.length/2);
index3 = (myArray.length/2 - 1);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index2 && j != index3)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
}
}
}
System.out.println(Arrays.toString(myArray));
}
}
You must create the array and populate it, else it's using the same memory address, hence won't work. Use the following:
myArray = ArrayUtils.clone(x);
When you are doing do “myArray = x”, your are actually merely assigning a reference to the array. Hence, if you make any change to one array, it would be reflected in other arrays as well because both myArray and x are referring to the same location in memory.
Thus, what you need is
myArray = x.clone();
I cleaned up your code a bit. According to what you described, what really matters is pulling in the minimum and maximum values in the array - everything else will be deleted, so you simply need a single traversal through the array to find those two values.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isValid = false;
int validLength = 0;
System.out.println("Please enter the array length:");
while (!isValid) {
int length = scanner.nextInt();
if (length < 3) {
System.out.println("Please make sure array length is greater than two. Try again.");
}
else {
isValid = true;
validLength = length;
}
}
int minimumValue = Integer.MAX_VALUE, maximumValue = Integer.MIN_VALUE;
for (int i = 0; i < validLength; i++) {
System.out.println("Please enter a number for position " + i + ":");
int nextInt = scanner.nextInt();
if (nextInt < minimumValue) minimumValue = nextInt;
else if (nextInt > maximumValue) maximumValue = nextInt;
}
System.out.println(Arrays.toString(new int[] {minimumValue, maximumValue}));
}
Edit: made another revision as using an array is unnecessary. Just keep track of the minimum and maximum values as they are being entered.
I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.
I have basically finished this piece of code, but when I print out the numbers from the array in the lottery class, I get a bunch of seeming gibberish. How can I fix the problem?
import java.util.Scanner;
public class Hw5pr2
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int[] rand = new int[5];
System.out.println("please enter 5 number");
for (int a = 0; a<rand.length; a++)
{
rand[a] = kb.nextInt();
}
Lottery k = new Lottery();
System.out.print("your number are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(rand[a]+",");
}
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+",");
}
System.out.println("you have " + k.RanInput(rand) + " matching number!!");
}
}
import java.util.Random;
public class Lottery
{
private int[] lotteryNumbers = new int[5];
public Lottery()
{
Random rand = new Random();
for (int a = 0; a<lotteryNumbers.length; a++)
{
lotteryNumbers[a] = rand.nextInt(9)+1;
}
}
public int RanInput(int[] Inran)
{
int b = 0;
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
}
public int[] getArray()
{
return lotteryNumbers;
}
}
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+","); //k.getArray() which returns you an entire array
}
You are trying to print the entire array. That's why it may show you the reference instead. You can store the array in a temp array and print the contents of that array.
You may try doing something like this:
int[] winningNum = k.getArray();
for (int a = 0; a < winningNum.length; a++)
System.out.print(winningNum[a] + ",");
try something like
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]+",");
}
note here
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
this is always return lotteryNumbers.length-1; beacause always two arrays are same
When you print out the array, to the best of my knowledge, it calls the toString method.
This returns a hash of the object, not the values it contains. You can call the static method toString from the Arrays class also to print the string values of the array.
System.out.print(Arrays.toString(k.getArray())+",");
or use a for loop
for (int a = 0; a < k.getArray().length; a++)
{
System.out.print(k.getArray()[a]+",");
}
A few things to note:
As others have mentioned, if you want to print the elements of an array, a simple way to do it is with a for loop. Your code won't work the way you want it to unless you access each element of k's lotteryNumbers array separately:
System.out.print("The winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]); //make sure to include the [a]
if(a != rand.length - 1) //added to help make prints more readable
System.out.print(", ");
}
Secondly, your RanInput function won't behave the way you want it to, assuming you wanted to see how many of the user's numbers match the lottery numbers. Currently, it just checks if the nth number inputted matches the nth lotto number chosen, which is unlikely to be true. Instead, you should do something like this:
public int RanInput(int[] Inran)
{
int count = 0;
for (int i = 0; i<lotteryNumbers.length; i++)
{
for(int j = 0; j < lotteryNumbers.length; j++) {
if (lotteryNumbers[j] == Inran[i])
{
count++;
}
}
}
return count;
}
It compares each of the inputted numbers with each of the lotto numbers. There are more efficient ways to do this than the code above, but I think it should be good enough for now.
I don't think the code you use to generate the lottery numbers account for duplicates (e.g. the numbers might be 1, 2, 2, 1, 3) so you should fix that.
Finally, here's some error checking you should implement if you want to be thorough:
make sure the user inputs exactly 5 numbers
all positive integers
are below some upper bound (say, 100)