For this program, I have a user input elements into a 5 space array using the private static void add() method. After adding these elements, the user is then able to use the private static void delete() method which allows them to input a number present in the array that they wish to remove. When entering numbers to remove, the program works perfectly fine unless I try to remove the last number for the currentSize of the array. For example, if I have an array with the following indexes and values:
0. = 1
1. = 2
2. = 3
3. = 4
4. = <empty>
The currentSize of the array is currently 4. If I try to remove value 4 in index 3, the program will not remove value 4. If I attempt to remove values 3, 2, or 1 after trying to remove value 4, these values will not remove either. On the other hand if I want to remove any of the values below value 4 first, i.e) values 1, 2, and 3, the program works correctly until I try to remove value 4 in index 0. If I attempt to remove value 4 at this point, nothing is removed. If I try to add a value, say 1, after attempting to remove value 4, value 4 is replaced with value 1. If I attempt to remove value 4 twice at index 0 and then attempt to add a new value, I get an IndexOutOfBoundsException: -1 . I believe that this has something to do with currentSize-- decrementing when it is not suppose to in the remove element algorithm present in the private static void delete() method. If anyone has a solution for this it would be greatly appreciated, thank you. The program is posted below. I have commented the section of the private static void delete() method that is giving me issues. This is the stack trace that I am getting:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at ArrayManager.add(ArrayManager.java:35)
at ArrayManager.main(ArrayManager.java:216)
/**
* A class that contains methods to carry out the Add, Update, Delete, Drop, Resize, and End commands to alter the state of an array with 5 integers.
*/
public class ArrayManager
{
// Array of 5 integers to be modified
private static int [] values = new int [5];
private static int currentSize = 0;
private static int position = 0;
//private static int index = 0;
static Scanner in = new Scanner(System.in);
/**
* A method that inserts an entered value into the array as long as it is between 1 and 99. If the array is full, an error message will be printed explaining that the array is full.
*/
private static void add()
{
System.out.println("Enter values between 1 and 99, inclusive that you would like to add to the array.");
if(in.hasNextInt())
{
int n = in.nextInt();
if(n >= 1 && n <= 99)
{
if(currentSize < values.length)
{
values[currentSize] = n;
currentSize++;
}
else
{
System.out.println("ERROR: The array is currently full.");
}
}
else
{
System.out.println("ERROR: The number entered must be between 1 and 99, inclusive.");
}
}
else
{
System.out.println("ERROR: String has been entered. Enter an Integer.");
}
}
/**
* A method that asks the user to enter a value they wish to delete in the array. The following values are then shifted down in index in the array. If the value chosen does not exist in the array, an error message is displayed explaining that the value entered does not exist in the array.
*/
private static void delete()
{
int n = 0;
System.out.println("Please enter the value in the array that you wish to remove.");
if(in.hasNextInt())
{
n = in.nextInt();
for(position = 0; position < values.length; position++)
{
if(values[position] == n)
{
// The stack trace points me back to this section of code which removes the specified value in the values array.
for(int i = position + 1; i < currentSize; i++)
{
values[i - 1] = values[i];
values[i] = 0;
}
currentSize--;
break;
}
else if(position == values.length - 1)
{
System.out.println("ERROR: The value entered does not exist in the array.");
}
}
}
else
{
System.out.println("ERROR: String has been entered. Enter an Integer.");
}
}
/**
* A method that prints out the modified array.
*/
public static void printArray()
{
System.out.println("* Current Array Contents *");
for(int i = 0; i < values.length; i++)
{
if(values[i] != 0)
{
System.out.println(i + ". = " + values[i]);
}
else if(values[i] == 0)
{
System.out.println(i + ". = <empty>");
}
}
}
The corner case where position is the index of last element of the values array, is not handled properly. In such a scenario, the code starts to iterate the elements from the next index in order to shift all the elements by 1 position and the condition is not met by the condition in for loop.
for(int i = position + 1; i < currentSize; i++)
for(int i = position + 1; i < currentSize; i++)
{
values[i - 1] = values[i];
values[i] = 0;
}
The solution would be to check for that condition and handle it explicitly.
if(values[position] == n ) {
if( position != values.length - 1 ) {
for(int i = position + 1; i < currentSize; i++)
{
values[i - 1] = values[i];
values[i] = 0;
}
} else {
values[i] = 0;
}
currentSize--;
break;
}
Related
I need to check if the numbers I stored in my LinkedList are in sequence.
Example sets are: 123, 124, 125, 1900, 1901.
If the code encounters the 123, it checks for the next which is 124 until 125 then stops since 1900 is not the next number after 125 when you are naturally counting. So I need to get the indexes of the first(123) and last sequence(125). Then on to the next sequence, 1900 and 1901.
for(int o = 0; o < zeroIndex.size(); o++)
{
if(-1 == (zeroIndex.get(o) - zeroIndex.get(o+1)))
{
System.out.println(zeroIndex.get(o) + "trailing");
}
}
String serialIndex = "";
for(int o = 1; o < zeroIndex.size(); o++)
{serialIndex += "("+Integer.toString(o-1);
while(i<zeroIndex.size() && zeroIndex.get(o-1)+1 == zeroIndex.get(o))
{ i++;
//System.out.println(zeroIndex.get(o) + "trailing");
}
serialIndex = serialIndex+Integer.toString(i-1)+"),";
}
System.out.println(serialIndex);
We will loop to the linked list and check if the previous is one less than current value.If this condition is true we will increment i else we will break will loop and add that i to ans
for example
123, 124, 125, 1900, 1901.
we will start from
124 ----- our serialIndex string will be (0 and 124 is one greater than 123 so we increment i. when we reach 1900 we will break the while loop as 1900 is not 1 greater than 125 and now our serialIndex string will b (0,2).
In the end we will have serialIndex string as (0,2),(3,4)
I do not have your full code to test so this is best i can do.If you encounter any error please let me know.
This works with O(n)
import java.util.LinkedList;
public class TestLinkedList {
public static void main(String[] args) {
LinkedList<Integer> a = new LinkedList<Integer>();
a.add(124);
a.add(125);
a.add(126);
a.add(1900);
a.add(1901);
int index = 0;
int index1 = 0;
for (int i = 0; i < a.size(); i++) {
if (i+1 < a.size() && a.get(i) + 1 == a.get(i + 1)) {
index1 = i + 1;
} else {
if (index != index1) {
System.out.println(index + " " + index1);
}
index = i+1;
index1 = i+1;
}
}
}
}
output
0 2
3 4
Here is a quick example on how to do it. First, create our list.
List<Integer> a = new LinkedList<Integer>();
a.add(124);
a.add(125);
a.add(126);
a.add(1900);
a.add(1901);
So, now that we have a list, let start. First, declaring our variables
int current; //will hold the current value during the iteration
int indexStart = 0; //the index of the beginning of the current sequence
int previous = a.get(0); //the previous value
int length = a.size(); //the length (optionnal, but this will be used later)
Then, here come the funny par (fully commented)
//Iterate from 1 to the end (0 is already in `previous`
for(int i = 1 ; i < length; ++i){
//get the current value
current = a.get(i);
//if the sequence is broken, print the index and print also the sublist using `List.subList`.
if(current != previous + 1){
System.out.format("Sequence from %d to %d%n", indexStart, i - 1);
System.out.println(a.subList(indexStart, i));
//reset the start of the current sequence
indexStart = i;
}
//update the previous value with the current for the next iteration.
previous = current;
}
//Print the last sequence.
System.out.format("Sequence from %d to %d%n", indexStart, length - 1);
System.out.println(a.subList(indexStart, length));
This will print :
Sequence from 0 to 2
[124, 125, 126]
Sequence from 3 to 4
[1900, 1901]
This is quite simple, just iterate the loop and keep the previous and current value to be able check if the sequence is correct or not.
Note that with a LinkedList, I would have used an Iterator but I need an int index so this would have give a longer solution, so to keep this simple, I used List.get.
What I have is a program that prints out 4000+ random digits in the range of 1 to 99999. After printing, it shows the range, and a couple of other things, and then asks user for 5 numbers to be input and tells how many times it had to run the loop, but I'm getting an exception in main upon print, it's coming from the main for loop. Screenshot is attached. Desired should look something like:
(Randomly generated numbers):
25
192
33
(User Enters) Please enter number: 33
(System Response) It took 3 times to find the number.
If the number is not listed, as it is over 4000 integers, it will say, not found.
Here is code and screenshot:
Screenshot
Exception in Main java.lang.ArrayIndexOutOfBoundsException:0
Thank You!
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] input = new int[0];
int[] arrayone = new int[4096];
int loop = 0;
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
for(int in = 0; in<input.length; in++) {
if (arrayone[i] == input[in]) {
loop++;
}
}
}
for (int i = 0; i < 5; i++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[0] = s.nextInt();
if (min <= input[0] && input[0] <= max) {
System.out.println("It took " + loop + " time(s) to find the number " + input);
}
}
}
The problem with your input array is that you initialize it with a size of 0, so when you try to access the first location [0], you run out of the bounds since your array has a size of 0. In your answer you were also trying to determine the loops before asking the question. While doing this you were also trying go past the bounds of your input array with a size 0. What you should do is initialize your array of numbers first then for each guess loop through and determine if it's within the bounds of your max and min. Also note that just because the numbers are within the max and min doesn't guarantee the number is contained in the array because the numbers are not going to be sequential from max to min. You should check where you end up after your for-loop check for the input.
public static void main(String random[])
{
Scanner s = new Scanner(System.in);
int input = new int[5];
int[] arrayone = new int[4096];
int loop = 0;
//don't do anything here except fill the array with values
for(int i = 0; i < arrayone.length; i++) {
arrayone[i] = (int)(Math.random() * 99999 + 1);
}
//ask the user for 5 inputs
for (int index = 0; index < input.length; index++) {
System.out.println("Please enter a number between " + min + " and " + max);
input[index] = s.nextInt();
//check to see if the number is valid
if (min <= input[index] && input[index] <= max) {
//loop through the arrayone to determine where it is
for(int i = 0; i < arrayone.length; i++) {
//if it is not in the current index at i increment the loop count
if (arrayone[i] != input[index]) {
loop++;
}
//we have found where it is and should break out of the loop
else {
break;
}
}
//check if we found it based on how much we incremented
if(i != arrayone.length)
{
//output how long it took to find the number
System.out.println("It took " + loop + " time(s) to find the number " + input[index]);
}
else
{
System.out.println(input[index] + " not found!");
}
//now reinitialize the loop to 0 for the next guess
loop = 0;
}
}
//always remember to close your scanners
s.close();
}
}
int[] input = new int[0];
This creates an array with size of 0, so when you try save value it throws an exception because you are exceeding array size.
Solution: set valid size of array or use list.
The ArrayList is (simplifying) resizeable version of array. Use it like this:
List<Integer> input = new ArrayList<>();
input.add(5); //Adds 5 to list
input.get(0); //Read object of index 0
for(int value : list) { //Loop: for each element in list ...
System.out.println(value);
}
//Checks whether list contains 5
System.out.println(list.contains(5));
Also, do you actually need input to be an array? Because right now it looks like you don't need it at all.
This question follows my brevious one on how to Return value of smallest index of repeated number in array.
In this function given to me by #Andreas:
private static void printFirstIndexOfRepeated(int[] values) {
Integer firstIndex = null;
Map<Integer, Integer> mapValueToIndex = new HashMap<>();
for (int i = 0; i < values.length; i++) {
Integer prevIndex = mapValueToIndex.put(values[i], i); // put() returns old value, or null
if (prevIndex != null && (firstIndex == null || prevIndex < firstIndex))
firstIndex = prevIndex;
}
if (firstIndex != null)
System.out.println("First index of repeated: " + firstIndex);
else
System.out.println("No repeat found");
}
Function test:
int [] array = {10,5, 4, 3, 5, 6};
printFirstIndexOfRepeated(array);
Output
First index of repeated: 1 // it looks for 5 and return the value of smallest index of repeated 5 in array.
Due to my lack of programming knowledge with Map, I'm new and I know only Array. I need some help to transform this function and add another parameter like (int number) to decide witch number I'm looking for and not automatically
The desired one: printFirstIndexOfRepeated(int[] values, int number)
So because you basically just want the index of the first occurrence of a given number inside an array, you don't need the Map at all. Instead you can just use a simple for loop:
private static int printFirstIndexOfRepeated(int[] values,int number) {
for(int i = 0; i < values.length; i++){
if(values[i] == number){
//System.out.println("The first index of " + number + " is " + i);
return i;
}
}
//System.out.println(number + " is not a member of the array.");
return -1;
}
This function returns the first index of a given number or -1 if the number was not found. You can uncomment the print lines to also get an output if you like (or just delete them).
Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
Whenever I am trying to run this code, it gives me out of bound exception. Can anyone point me out what's wrong with it.
package com.programs.interview;
import java.util.Scanner;
public class FindMaxNumInArray {
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < arraySize; i++)
myArray[i] = scan.nextInt();
for (int j = 0; j < arraySize; j++)
System.out.println(myArray[j]);
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
}
public static int maximum(int[] arr, int Arraylength){
int tmp;
if (Arraylength == 0)
return arr[Arraylength];
tmp = maximum(arr, Arraylength -1);
if (arr[Arraylength] > tmp)
return arr[Arraylength];
return tmp;
}
}
Output
Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3
4 5 1 2 3 4 5 Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26)
at
com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17)
This is the problem:
if (arr[Arraylength] > tmp)
Valid array indexes go from 0 to length-1 inclusive. array[array.length] is always invalid, and on the initial call, ArrayLength is equal to arr.length.
It's not clear why you're using recursion at all, to be honest. An iterative solution would be much simpler - but you'll need to work out what you want to do if the array is empty.
EDIT: If you really want how I would write the recursive form, it would be something like this:
/** Returns the maximum value in the array. */
private static int maximum(int[] array) {
if (array.length == 0) {
// You need to decide what to do here... throw an exception,
// return some constant, whatever.
}
// Okay, so the length will definitely be at least 1...
return maximumRecursive(array, array.length);
}
/** Returns the maximum value in array in the range [0, upperBoundExclusive) */
private static int maximumRecursive(int[] array, int upperBoundExclusive) {
// We know that upperBoundExclusive cannot be lower than 1, due to the
// way that this is called. You could add a precondition if you really
// wanted.
if (upperBoundExclusive == 1) {
return array[0];
}
int earlierMax = maximumRecursive(array, upperBoundExclusive - 1);
int topValue = array[upperBoundExclusive - 1];
return Math.max(topValue, earlierMax);
// Or if you don't want to use Math.max
// return earlierMax > topValue ? earlierMax : topValue;
}
you can't access
arr[Arraylength]
the last element would be at
arr[Arraylength -1]
for example if you have
int arr[] = new int[5];
then the elements would be at 4, because index starts from 0
arr[0], arr[1], arr[2], arr[3], arr[4]
Your issue is in the following piece of code:
if (arr[Arraylength] > tmp)
return arr[Arraylength];
Indexes start at 0, so you will be out of bound for an array with 5 elements [1,2,3,4,5] indexes: [0,1,2,3,4].
I would use a plain loop. Java doesn't do recursion particularly well.
public static int maximum(int[] arr) {
int max = Integer.MIN_VALUE;
for(int i : arr) if (i > max) max = i;
return max;
}
here
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
you are passing the arraysize where in maximum method you are returning arr[Arraylength] which giving ArrayIndexOutOfBound so change either in calling maximum(yArray,arraySize-1) or return arr[Arraylength-1] statement.