Array find an index of scanner integer - java

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);
}

Related

"Index was not found" program in Arrays

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);
}
}

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]++;

Trying to swap array elements based on user input

So I have to swap two elements in an array with 5 values but the two to swap have to be taken from the keyboard. The previous question was to swap to specific ones and I got it done but I'm not sure how to get the numbers from the keyboard to be used in the swap. Some of this is left from the previous one where I knew the elements I had to swap.
import java.util.Scanner;
public class Swap2 {
public static void main(String []args) {
Scanner keyboardIn = new Scanner (System.in);
int[] numbers = new int []{12,9,33,28,5};
int temp = 0, first, second;
System.out.println ("Before the swap: ");
for(int i=0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println ("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println ("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println ();
temp = numbers[3];
numbers [3] = numbers [1];
numbers [1] = temp;
System.out.println ("After the swap:");
for (int i = 0; i < numbers.length; i++) {
System.out.print (numbers[i] + " ");
}
}
}
you have to define index...
import java.util.Scanner;
public class Swap {
public static void main(String[] args) {
Scanner keyboardIn = new Scanner(System.in);
/* enter code here */int[] numbers = new int[] { 12, 9, 33, 28, 5 };
int temp = 0, first, second;
int index1 = 0 , index2 = 0;
int j , k ;
System.out.println("Before the swap: ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println();
for(k = 0 ; k < numbers.length; k++){
if(numbers[k] == first)
index1 = k;
}
for(j = 0 ; j < numbers.length; j++){
if(numbers[j] == second)
index2 = j;
}
temp = numbers[index1];
numbers[index1] = numbers[index2];
numbers[index2] = temp;
System.out.println("After the swap:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
You're not actually swapping the numbers which user enters, you're always swapping 4th element with the 1st.
To swap the elements you need to find out the index where they belong.
public static int indexOf(int []arr, int ele)
{
for(int i = 0; i < arr.length; ++i)
if(arr[i] == ele)
return i;
return -1;
}
Now to swap those elements, call this function.
int first = sc.nextInt();
int firstIndex = indexOf(arr, first);
int second = sc.nextInt();
int secondIndex = indexOf(arr, second);
int temp;
temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;
Why don't you try this. Please keep in mind that array indices start at 0.
import java.util.Scanner;
public class Swap2
{
public static void main(String []args)
{
Scanner keyboardIn = new Scanner (System.in);
int[] numbers = new int []{12,9,33,28,5};
int temp, first, second;
System.out.println ("Before the swap: ");
for(int i=0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
System.out.println ();
System.out.println ("Enter the first number to swap:");
first = keyboardIn.nextInt();
System.out.println ("Enter the second number to swap:");
second = keyboardIn.nextInt();
System.out.println ();
temp = numbers[first];
numbers [first] = numbers [second];
numbers [second] = temp;
System.out.println ("After the swap:");
for (int i = 0; i < numbers.length; i++)
{
System.out.print (numbers[i] + " ");
}
}
}

Insertion sort: count swaps and comparisons

For some reason I can't get the count for comparisons and swap in the InsertionSort part, it just outputs zero. And when I isolate the code for it, it outputs a number of swaps and comparisons (though I don't know if it's wrong or not, probably wrong considering the number is the same for both) and the array is not sorted at all. I'm really confused as to why this isn't working, any help is greatly appreciated!
Update: The instance of bubble was being passed onto both selection and insertion, now that that's fixed turns out T also have a problem with the selection part. Any suggestions on how to fix them?
Update 2: Fixed the selection part! Still confused about insertion.
import java.util.Scanner;
public class Sorting {
public static void main(String[] args) {
int n, c;
Scanner scan = new Scanner(System.in);
System.out.print("Number of elements: ");
n = scan.nextInt();
int[] bubbleSortArray = new int[n];
int[] selectionSortArray = new int[n];
int[] insertionSortArray = new int[n];
System.out.print("Enter " + n + " elements: ");
for (c = 0; c < n; c++) {
int i = scan.nextInt();
bubbleSortArray[c] = i;
selectionSortArray[c] = i;
insertionSortArray[c] = i;
}
BubbleSort(bubbleSortArray);
SelectionSort(selectionSortArray);
InsertionSort(insertionSortArray);
}
static void BubbleSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int c = 0; c < (n - 1); c++) {
for (int d = 0; d < n - c - 1; d++) {
cm++;
if (array[d] > array[d + 1]) {
int swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
sw++;
}
}
}
System.out.print("Bubble sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
static void SelectionSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int c = 0; c < n - 1; c++) {
int index = c;
for (int d = c + 1; d < n; d++){
cm++;
if (array[d] < array[index])
index = d;
}
int temp = array[index];
sw++;
array[index] = array[c];
array[c] = temp;
}
System.out.print("Selection sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
static void InsertionSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int c = 1; c < n; c++){
int temp = array[c];
for (int d = c - 1; d > 0 && temp < array[d]; d--) {
array[d+1] = array[d];
array[d+1] = temp;
cm++;
sw++;
}
}
System.out.print("Insertion sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
}
After you are done with BubbleSort array is sorted, and you are passing that sorted instance to SelectionSort and InsertionSort.
If you want to get the results for each kind of sorts you can do :
int n, c;
Scanner scan = new Scanner(System.in);
System.out.print("Number of elements: ");
n = scan.nextInt();
int[] bubbleSortArray = new int[n];
int[] selectionSortArray = new int[n];
int[] insertionSortArray = new int[n];
System.out.print("Enter " + n + " elements: ");
for (c = 0; c < n; c++) {
int i = scan.nextInt();
bubbleSortArray[c] = i;
selectionSortArray[c] = i;
insertionSortArray[c] = i;
}
BubbleSort(bubbleSortArray);
SelectionSort(selectionSortArray);
InsertionSort(insertionSortArray);

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]);
}
}

Categories