"Index was not found" program in Arrays - java

I write a program that has a list of numbers. You need to add code to find a specific number in the list. If the number is found, the program will show its location. If the number is not found, the program will say that it couldn't be found.
The problem is, the output is looping, and I don't want that.
int[] array = new int[10];
array[0] = 6;
array[1] = 2;
array[2] = 8;
array[3] = 1;
array[4] = 3;
array[5] = 0;
array[6] = 9;
array[7] = 7;
System.out.print("Search for? ");
int searching = in.nextInt();
for(int i=0; i<array.length; i++){
if(searching == array[i]){
System.out.println(searching + " is at index " + i + ".");
break;
}
else{
System.out.println(searching + " was not found.");
}
}
My output:
Search for? 1
1 was not found.
1 was not found.
1 was not found.
1 is at index 3.
Expected output:
1 is at index 3.

import java.util.Scanner;
public class IndexWasNotFound {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
array[0] = 6;
array[1] = 2;
array[2] = 8;
array[3] = 1;
array[4] = 3;
array[5] = 0;
array[6] = 9;
array[7] = 7;
int index = 0;
String ans = null;
boolean yn;
System.out.print("Search for? ");
int searching = scanner.nextInt();
for(int i=0; i<array.length; i++) {
if (searching == array[i]) {
index = i;
ans = searching + " is at index " + index + ".";
yn = true;
break;
} else {
ans = searching + " was not found.";
yn = false;
}
}
System.out.println(ans);
}
}

Related

Array find an index of scanner integer

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[5];
array[0] = 1;
array[1] = 3;
array[2] = 5;
array[3] = 7;
array[4] = 9;
System.out.println("Search for?");
int searchFor = scanner.nextInt();
for(int i = 0; i < array.length;i++)
if(array[i] == searchFor)
System.out.println(searchFor + " is at index " + i);
else {
System.out.println(searchFor + " was not found");
}
I have just trouble with this and didn't find the way I can do it because most of examples require to use other functions.
But I have primitive array and I need to get an index given number by user and if it does not exist it should return was not found
so the problem is that my program screening all of elements all the way down and showing up 5 outcomes when I need only two outcome whether it exist in given index or not.
Scanner scanner = new Scanner(System.in);
int[] array = new int[5];
array[0] = 1;
array[1] = 3;
array[2] = 5;
array[3] = 7;
array[4] = 9;
System.out.println("Search for?");
int searchFor = scanner.nextInt();
int index=-1;
for(int i = 0; i < array.length;i++) {
if (array[i] == searchFor) {
index = i;
}
}
if(index==-1){
System.out.println(searchFor + " was not found");
}else{
System.out.println(searchFor + " is at index " + index);
}

explaining this simple program - bucket sort

What does int[] a do in this code?
public class BucketSort_main {
public static void main(String[] args) {
int[] numbers = new int [5]; //create an array to house the numbers generated
int[] sortedArray = new int [5]; //create array to be a temp housing for the numbers
int [][] bucket = new int [10][numbers.length]; //creates 2D array of 0-9
int [] a = new int [10];
int divisor = 1;
int digitCount = 1;
boolean moreDigits = true;
//fill the array and array to be sorted with the random numbers 0 - 100
for (int i = 0; i < numbers.length; i++) {
numbers [i] = (int)(Math.random()*100);
sortedArray [i] = numbers [i];
}
System.out.println("UnSorted Numbers");
for (int i = 0; i< numbers.length; i++){
System.out.println (numbers[i]);
}
}
System.out.println("\n");
int[] tempArray = new int[10]; //creatE a temp array of size equal to the amount of buckets
while (moreDigits) {
moreDigits = false;
for (int i = 0; i < tempArray.length; i++){
tempArray[i]= -1; //initailze to make sure a null pointer is not hit
}
for (int i = 0; i < numbers.length; i++){
int tmp = sortedArray[i] / divisor; //create a temp int of the array value / divisor to get its single digit value
if (tmp/10 != 0){
moreDigits = true;
}
int numPlace = tmp % 10;
tempArray[numPlace] = sortedArray[i]; //at the digits "ones"/tens value for row index, set the number from the sorted array into that index
bucket [numPlace][a[numPlace]] = sortedArray[i]; //place the numbers into the proper coord of the bucket.
//Print statements used for DEBUGGING
System.out.println("Number: " + tempArray[numPlace] +" Has Digit "+digitCount+" equal to "+ numPlace);
// bucket [digit][a[digit]] = tempArray[i];
//row may seem "off" to user, but the row prints based on 0 - n
System.out.println ("Digit " + numPlace + " moved into row " + a[numPlace] + ". " + bucket[numPlace][a[numPlace]]);
System.out.println (" ");
a[numPlace]++;
}
digitCount++;
divisor *= 10; //multipy the divisor by 10 to move to the next 1s. 10s, or 100s place
int j = 0; //iteration for tempNumbersArray
for (int x = 0; x < 10; x++) {
a[x] = 0;
for (int y = 0; y < numbers.length; y++){
if (bucket[x][y] != 0) {//see if value in bucket is a zero, if it is dont print it
sortedArray [j] = bucket[x][y]; //set sorted array value equal to the value at row/col index of bucket
bucket[x][y] = 0; //set that spot that was just copied over to zero
j++; //increment to the next index of sorted array
}
}
}
} //end while
System.out.println("Sorted Numbers:");
for (int i = 0; i < numbers.length; i++) {
System.out.println (sortedArray[i]);
}
}
The 'a' array holds the number of entries that a certain bucket holds. Each time something is added to bucket x, the value of a[x] is incremented with one.
So 'a' is only used to do some bookkeeping. This can be avoided by changing
bucket [numPlace][a[numPlace]] = sortedArray[i];
in
bucket [numPlace][bucket[numPlace].length] = sortedArray[i];
and
System.out.println ("Digit " + numPlace + " moved into row " + a[numPlace] + ". " + bucket[numPlace][a[numPlace]]);
in
System.out.println ("Digit " + numPlace + " moved into row " + bucket[numPlace].length + ". " + bucket[numPlace][a[numPlace]]);
and by removing
a[numPlace]++;

Numbering Array items numerically

Alright, so I tried implementing the bubble sort algorithm into my code, but now my output for the second array (in my code) is giving me a ton of zeros. Can anybody tell me what is wrong with my code and how I can fix it so the zeros are removed and the only thing that remains in the output for my second array are the fixed numerically?
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
scan.close();
}
}
}
Copy your array1 to an array2 of the correct length before sorting, something like
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
}
array1[i] = input;
}
int[] array2 = Arrays.copyOfRange(array1, 0, i);
System.out.println("Before sorting: " + Arrays.toString(array2));
Arrays.sort(array2); // <-- How I would sort.
System.out.println("After sorting: " + Arrays.toString(array2));
The reason this is necessary is because i might not be 10 in which case your array contains 0(s) to fill the other positions.
Is it possible to move all my numbers from Array 1 to Array 2 using a for-loop?
Yes. You could implement a copyOfRange function with a for loop,
private static int[] copyOfRange(int[] arr, int start, int end) {
int pos = 0;
int[] out = new int[end - start];
for (int i = start; i < end; i++) {
out[pos] = arr[i];
pos++;
}
return out;
}
the built-in version is almost certainly better.
1) You are printing the array multiple times, I think you might be giving 0 as input and thats the reason you are seeing 0's everywhere.
2) You have created array2 which is not necessary.
Move the printing logic out of for loop as in the below snippet. Otherwise your logic looks fine except fot the wrong looping of print statement.
public static void main(String args[]) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
scan.close();
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
}

java 2D array search/sort/add

I have to take in a few ID numbers and how many boxes sold by the ID number...split those into two arrays...which I've done....then sort the array reporting the largest sale of boxes sold....the(and this is my problem) if the same id number is entered, add the number of boxes sold together and make it take up only one spot in the array
example....
idNum 1 = 100
idNum 3 = 500
idNum 1 = 200
so idNum 1 = 300
//declarations
int [][] stupidKids = new int[10][2];//10 rows....2 columns
int entry = 0;
int tempNum;
int tempTotal = 0;
int tempId;
int found = -1;
//user input section
for(int i = 0; i < 2; i++)
{
System.out.print("Please enter the class ID");
Scanner scan = new Scanner(System.in);
stupidKids[i][0] = scan.nextInt();
System.out.print("Please enter the amount of cookies sold");
stupidKids[i][1] = scan.nextInt();
System.out.println(stupidKids[i][0] + "Cookies " + stupidKids[i][1]);
}
//sorting process
for(int i = 0; i < 2; i++)
{
if(stupidKids[i][1] > stupidKids[i+1][1])
{
tempNum = stupidKids[i][1];
stupidKids[i][1] = stupidKids[i + 1][1];
stupidKids[i + 1][1] = tempNum;
tempId = stupidKids[i][0];
stupidKids[i][0] = stupidKids[i+1][0];
stupidKids[i+1][0] = tempId;
}
}
//comparing for same ID Num
for(int i = 0; i < 1; i++)
{
if(stupidKids[i][0] == stupidKids[i+1][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[i+1][1]);
}
}
System.out.println("Final num " + tempTotal);
You must loop through your for loops 10 times rather than just twice, this way you get through the whole array.
for(int i = 0; i < 10; i++)
Below is the code to compare the IDs against each other in the 2D array. Although I am not quite sure about why you would want it to take up only one space per ID as you will end up with a lot of NULL values in the array as you can not easily resize an array (to do this requires an implementation of a basic algorithm)
for(int i = 0; i < 10; i++)
{
tempID = stupidKids[i][0];
for(int j = 0; j < 10; j++)
{
if( i != j)
{
if(stupidKids[i][0] == stupidKids[j][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[j][1]);
}
}
}
}
System.out.println("Final num " + tempTotal);

Simple Java Fibonacci code issue

import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i<count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i<count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
This is my very simple Fib program, what i cant figure out is why it always stops one number short. For example:
run: Please enter number 6 1 1 2 3 5 8 BUILD SUCCESSFUL (total time: 5
seconds)
run: Please enter number 7 1 1 2 3 5 8 13 BUILD SUCCESSFUL (total
time: 5 seconds)
I thought in my FOR loops it should be "(int i=2; i <= count;"
but when i put in greater than or equal to in both, or either FOR loop it gives me an error
Any suggestions? i know its something easy i'm overlooking
Your code is giving correct output. but still if you need one more element try to initialize array with count + 1 and then have your loop running for i <= count
public static void main(String[] args) {
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count+1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++){
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i <= count; i++){
System.out.print(fib[i] + " ");
}
}
}
Arrays are zero-based. This means, that (assuming count = 5) if you have the following array:
int[] fib = new int[5];
then you can access fib[0], fib[1], fib[2], fib[3] and fib[4]. So
for (int i = 0; i < 5; i++) {
System.out.print(fib[i] + " ");
}
would be fine. As it would access everything in fib, starting with index 0, and stopping with the last index smaller than 5, which is 4. However, if you do:
for (int i = 0; i <= 5; i++) {
System.out.print(fib[i] + " ");
}
then you will access the last index smaller than OR EQUAL TO 5, which is 5. But, as stated before, fib[5] is invalid. That's what gives you your error.
A simpler solution is to avoid needing an array in the first place and you don't need to get the size right.
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
int count = in.nextInt();
long a = 1, b = 1;
for(int i = 0; i < count; i++) {
System.out.print(a + " ");
long c = a + b;
a = b;
b = c;
}
System.out.println();
}
There should be one more array element space for int fib[], thus the fib[count] could be stored.
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count + 1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = 0; i<= count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
public class Fibonacci
{
private int [] fibArray;
public Fibonacci()
{
}
public void Fibonacci()
{
fibArray = new int[0];
}
public void setFibonnaci(int size)
{
fibArray = new int[size];
if(fibArray.length == 1)
{
fibArray [0] = 0;
}
else if(fibArray.length == 2)
{
fibArray[0] = 0;
fibArray[1] = 1;
fibArray[2] = 2;
}
else
{
fibArray[1] = 1;
fibArray[0] = 0;
for(int x = 2; x < fibArray.length; x++)
{
fibArray [x] = fibArray[x-1] + fibArray[x-2];
}
}
}
public int getSequence(int number)
{
if(number -1 < fibArray.length)
{
return fibArray[number - 1];
}
return -1;
}
//check the test case for getFibo
public String toString()
{
String output = "";
for (int x = 0; x < fibArray.length; x++)
{
output += x + " - " + fibArray[x];
}
return output;
}
}
Late response but new to site and just trying to help. This fib class works 100%

Categories