Find occurrence of element in array in Java - java

When the user types a value it checks if it exists in an array.
import java.util.Scanner;
public class array1 {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value");
int num = scan.nextInt();
int [] arraynumbers = {1,2,3,4,5,6,7,8,9,10};
for(int i = 0; i < arraynumbers.length; i++) {
if (arraynumbers[i] == num){
System.out.println("The value you have entered " + num + ", exists in the array");
}else{
System.out.println("The value you have entered does not exist in the array");
}
}
}
}
So, when ever I type a number to test it prints:
Enter a value
3
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered 3, exists in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
I am not 100% sure why this happens.
Questions
Is it because there is nothing stopping it from finishing when it finds a number in the array?
Is there a way to prevent this?
Thank you

You are probably looking out for a break. The entire loop is traversed even if your num is found. And either of the if or else block is executed. This would help you :
if (arraynumbers[i] == num) {
System.out.println("The value you have entered " + num + ", exists in the array");
break;
}
and probably to avoid printing anything in case the value is not matched you can remove the else block from your code.

The break statement is definitely key. However, if you want to print whether the number is found or not, you may want to consider something like this:
int num = scan.nextInt();
int [] arraynumbers = {1,2,3,4,5,6,7,8,9,10};
String srchStr = "does not exist";
for(int i = 0; i < arraynumbers.length; i++) {
if (arraynumbers[i] == num) {
srchStr = "exists";
break;
}
}
System.out.println("The value you have entered " + num + ", " + srchStr + " in the array");

When you put that check in a loop like this, it means you check every number in the array:
for(int i = 0; i < arraynumbers.length; i++) {
}
You could do this:
List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
if (values.contains(num)) {
System.out.println("The value you have entered " + num + ", exists in the array")
} else {
System.out.println("The value you have entered does not exist in the array");
}

Related

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

How do you check if inputted array values are the same?

My program is supposed to make sure each value the user enters is between 10-100. The value is then stored in the array. That part works fine. The other condition is that the value the user enters has to be different from all the other arrays. ie...array[0]=20 so all of the other arrays can no longer equal to be set to 20. I've been trying to solve this but I'm just not sure where to go. I tried setting statements after my while(userInput < 10 || userInput > 100) to check for any repeats and that worked. The problem was then the user could enter values less than 10 and greater than 100. Any help would be greatly appreciated!
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
for(int x = 0; x < array.length; x++)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
while(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100: ");
userInput = input.nextInt();
}
array[x] = userInput;
System.out.println(array[x]);
counter++;
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
}
You should get rid of the for and second while loop, and check if the value entered is in the desired range.
If it is, you verify for duplicates, store it in the array and increment the counter. If it’s not, you show the bad input message.
Either way, it continues to ask for an valid input until the counter gets to 5.
I hope it helps!
I changed your logic a little bit, see if you can understand it
(There are better ways of doing this, but I think this is more understandable)
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
if(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100.\n");
}
else {
//This is a valid input, now we have to check whether it is a duplicate
boolean isItDuplicate = false;
for(int i = 0; i < counter; i++)
{
if(userInput == array[i])
{
isItDuplicate = true;
}
}
if(isItDuplicate == true)
{
System.out.print("Please enter a number that is not a duplicate.\n");
}
else
{
array[counter] = userInput;
System.out.println(array[counter]);
counter++;
}
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
Don't use variable counter when var x does the same thing for you.
Don't use nested loops when the limiting condition of both loops need to be checked together in each iteration. Merge those loops into one wherever possible.
First of all, get rid of your nested loops. They're redundant. Let's look at your problem's specification. Your input needs to fulfill 3 requirements:
Be greater than or equal to 10
Be less than or equal to 100
Be a unique element inside the array
The first two conditions are simple enough to check. For the final condition, you need to search the values inside the array and see if there are any matches to your input. If so, the input is invalid. A simple way to approach this is to check every member of the array and to stop if a duplicate is found. There are better, more efficient ways to do this. Don't be afraid to search the internet to learn a searching algorithm. Below is a simple solution to your problem. It's far from ideal or efficient, but it's easy enough for a beginner to understand.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
int userInput;
while(counter < 5) {
System.out.print("Enter a number between 10 & 100: ");
userInput = in.nextInt();
if( (userInput >= 10 && userInput <= 100) && !searchDuplicates(array, userInput) ) {
array[counter] = userInput;
counter++;
} else {
System.out.println("Invalid value entered");
}
}
for(int i = 0; i < array.length; i++)
System.out.println("Value " + (i + 1) + ": " + array[i]);
}
private static boolean searchDuplicates(int[] array, int input) {
for(int i = 0; i < array.length; i++)
if(array[i] == input)
return true;
return false;
}
}

How to make for loop stop when scanner is at the very end of the input

I'm currently trying to make a program that will allow the user to enter any amount of integers (I'm only asking them to enter 9 for now as a test) and have the rotateArray function rotate the array of integers. For example:
input: 1 2 3 4 5
output: 5 4 3 2 1
The reason as to why I included the arraylist is because I want to make the program dynamically allocate memory so that the user can enter as many single digit inputs as well. My problem is with a for loop I'm currently using. I"m looking for a way to properly make it so that the for loop stops when it hits the very end of the user's input. I tried using scan.nextInt().isEmpty() but that did not work as intended.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("This program takes two arrays, compares them, and "
+ "determines whether the original array has been rotated and put "
+ "into another array. \nWatch what happens when the original "
+ "array = [0,1,2,3,4,5,6,7,8,9] is compared to an array with contents: \n"
+ "[9,7,5,3,1,8,6,4,2,0]");
int[] original = {0,1,2,3,4,5,6,7,8,9};
int[] notRotated = {9,7,5,3,1,8,6,4,2,0};
int[] rotatedArray = {9,8,7,6,5,4,3,2,1,0};
boolean rotation;
rotation = isRotated(original, rotatedArray);
if(rotation == true)
{
System.out.println("The original array has been rotated!");
}else{
System.out.println("The original array has not been rotated");
}
System.out.println("\n Watch what happens when the original array is compared to an array"
+ " with contents \n [9,8,7,6,5,4,3,2,1,0]");
rotation = isRotated(original, rotatedArray);
if(rotation == true)
{
System.out.println("The original array has been rotated!");
}else{
System.out.println("The original array has not been rotated");
}
ArrayList<Integer> userArray = new ArrayList<Integer>(9);
System.out.println("This program can also rotate arrays that contain "
+ "single digit integers.\n Enter 9 single digit "
+ "integers separated by spaces");
//*****************************************************
userArray.add(scan.nextInt());
for(int i = 0; i<userArray.size(); i++)
{
//*****problem
if(???????? )
break;
else
userArray.add(scan.nextInt());
}
System.out.println("The array you entered is: " + userArray.toString() +"\n");
rotateArray(userArray);
System.out.println("When your array is rotated, it looks like this: \n" +
userArray.toString());
}
public static ArrayList<Integer> rotateArray(ArrayList<Integer> userArray)
{
int replace = 0;
int inc = 1;
int indexVariable = 0;
//if number of elements equals an even number
if(userArray.size() % 2 == 0)
{
for(int i = 0; i < (userArray.size()/2);i++)
{
replace = userArray.get(i);
userArray.set(userArray.get(i),userArray.size() - inc );
userArray.set(userArray.size() - inc, replace);
inc++;
}
}
//if number of elements equals an odd number
else
{
for (int i = 0; i <(userArray.size()/2) ; i++)
{
replace = userArray.get(i);
userArray.set(userArray.get(i),userArray.size() - inc );
userArray.set(userArray.size() - inc, replace);
inc++;
}
}
return userArray;
}
The thing about the scanner is that when its reading from the console, #hasNext will only ever return false if the scanner is closed, such as when you close it or the console is no longer usable for input. Otherwise, calling it will tell the scanner to wait for input and will let you know if it is valid input (e.g if you call #hasNextInt).
So the best way IMO to solve your issue is to read the scanner as a string, then split it and process it yourself as follows.
String input=scan.nextLine();
String[] numbers=input.split(" ");
for(String number:numbers)
{
if(number.isEmpty())
continue;//check for trailing so input like 3 4 5 is read
userArray.add(Integer.parseInt(number));//You would want to add a catch here for invalid input.
}
If input: 1 2 3 4 5 and userArray.size should match original.length then you can do like this:
int size = original.length;
for (int i = 0; i < size; i++) {
int num = scan.nextInt();
userArray.add(num);
Or you can hardcode variable size:
int size = 9;
or input it from console:
int size = scan.nextInt();

Error Handling (Java)

Fairly easy question, but I was basically given code to debug and I've fixed all errors but one. When trying to make the program more friendly and include error handling, I found that the error message is thrown even if the condition is satisfied (that is, the number in the array that a user searches for actually exists within the array). Not looking for a direct answer, just a hint. I've tried using combinations of if/else as well as moving around curly braces.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
for (int i = 0; i < array.length; i++) {
if ( array[i] == number )
System.out.println("Found " + number + " at index " + index++);
}
System.out.printf("Your number was not found within the array.");
}
catch (InputMismatchException e){
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
}
Console output example:
Enter an integer to find: -9
Found -9 at index 0
Your number was not found within the array.
Array.binarySearch will return the index if it finds the value, otherwise it will return -1.
If index == -1, you can print the "not found message" without entering the loop at all.
Otherwise, if index > 0, then you can enter the loop and iterate over the array to find each index where the value is a match.
This is required if you want a message for multiple matches as binarySearch will just return the the first index the value was found at.
As an aside, binarySearch requires the array to be sorted first, otherwise the results will be undefined. I don't know if this is a problem as array is declared outside of the example.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
if (index > 0) {
for (int i = 0; i < array.length; i++) {
if ( array[i] == number ) {
System.out.println("Found " + number + " at index " + i);
}
}
} else {
System.out.printf("Sorry, your number wasn't found.");
}
}
catch (InputMismatchException e) {
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
in your code:
"Your number was not found within the array." will always be printed unless there is an exception caught by catch block
also one interesting thing about binary search is :
if an element is not present in the array, it returns negative of the probable position if the searched element "would have been" present.
Example : in this program, if you search for 9,it will return -3
if you search for 65,it will return -6
This will work correctly:
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class debug {
public static void main(String...args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
int i, array[]={-9,8,14,56,64};
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
if(index>=0)
System.out.println("Found " + number + " using binary search at index " + index);
else
System.out.println("Not Found !! index returned by binary search is : "+index);
boolean flag=false;
for (i = 0; i < array.length; i++) {
if ( array[i] == number ){
flag=true;
break;
}
}
if(flag)
System.out.println("Found " + number + " using for loop at index " + i);
else
System.out.printf("Your number was not found within the array.");
}
catch (InputMismatchException e){
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
}
}
The condition inside the loop is wrong. If the first element of the array isn't the value you were looking for, it immediately terminates. The error handling must be after the loop. Try this:
boolean found = false;
for (int i = 0; i < array.length; i++) {
if ( array[i] == number ){
System.out.println("Found " + number + " at index " + index++);
found = true;}
}
if(!found)
throw new IllegalArgumentException("Your number was not found within the array.");

Deleting element from an array in java

I created a program where users enter a command which are : adding a number to the array or delete an element from the array or print the array. The array size is 10.
Here is the tester class,
import java.util.Scanner;
public class Assignment7 {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
final int MAX = 10;
Numbers nums = new Numbers(MAX);
char command;
int value;
System.out.println
("To add an element into the array, type a.");
System.out.println
("To delete an element from the array, type d.");
System.out.println
("To print the current contents of the array, type p.");
System.out.println
("To exit this program, type x.\n");
System.out.print
("Add (a), delete (d), print (p) or exit (x)?:");
command = scan.nextLine().charAt(0);
while (command != 'x') {
if (command == 'a' || command == 'd') {
System.out.print ("Enter a number: ");
value = scan.nextInt();
scan.nextLine();
if (command == 'a')nums.add(value);
else nums.delete(value);
}
else if (command == 'p') nums.print();
else System.out.println ("Not a value input");
System.out.print
("Add (a), delete (d), print (p) or exit (x)?: ");
command = scan.nextLine().charAt(0);
}
System.out.println ("Program Complete");
}
}
And here is my other class,
import java.util.*;
public class Numbers{
private int[] nums;
private int size;
public Numbers(int _size){
this.nums = new int[_size];
}
public void add(int addnum){
if (size == nums.length)
{
System.out.println("Array is full. The value " +addnum + " cannot be added.");
}
else
{
nums[size] = addnum;
size += 1;
}
}
public void delete(int deleteNum){
if(search(deleteNum) == -1)
{
System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
}
else {
for (int i = nums[deleteNum]; i < nums.length -1; i++){
nums[i]= nums[i+1];
}
}
}
public void print(){
String output ="";
for(int str: nums){
output = output + " " + str;
}
System.out.println(output);
}
private int search(int x){
int index = 0;
while(index < size){
if(nums[index] == x)
return index;
index++;
}
return -1;
}
}
Each time I run the program and input a number I want to delete it doesn't delete it. It deletes the number in the index.
For example, if the array inputs are 1,2,3,4,5,6,7,8,9,10 and I want to delete the number 1 it deletes the value that is in the index of 1 which would be the number 2 instead of the number 1.
I think that your "design" is not efficient. Because in your small program your array size is changing during runtime. Also your delete method is "weird".
Why it's not efficient?
You're using static array that has fixed size -> so if you want to "correctly" delete item from it, you need to re-initialise new array with new (size - 1)1 and this is such a spaghetti code operation.
And what is a suggestion?
What about to use dynamic array that can change its size dynamically when you'll remove or add new item to it? It also offers directly methods like add and remove for manipulating with it.
1You need to reinitialise static array (with new size - 1) again because if you'll "delete" for example 2. item from it it will be only assigned to zero so whole array will looks like: [ 1, 0, 3, 4, 5, 6, 7, 8, 9 ] and desired goal is [ 1, 3, 4, 5, 6, 7, 8, 9 ]
tl;dr: use an ArrayList, or seperate your array operations into its own class.
If you want to be able to add to and delete from a list, you most probably want to use an arraylist, which is implemented with an array "beneath the hood", but it supports a dynamic size.
The most valid reason for you to use an array, and not some sort of collection is for learning purposes, in which case you should make your own "arraylist" so all code related to add/deleting/etc is contained within its own class. Just know that your implementation is probably never gonna be as efficient and robust as ArrayList.
When deleting elements you do not need to "resize" the array, only keep a seperate size variable which tells you which indeces are "valid". When adding new elements you have to initialize a new array with a greater size, if you have exceeded the array's length, and copy over all the elements from the old one.
In your delete method, you should store the value you get from your search method. Right now you are calling nums[deleteNum] which is using the number inputted as an index. This is why you are having value 2 deletes. you should do something like this:
public static void delete(int deleteNum){
int index = search(deleteNum);
if(index == -1)
{
System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
}
else {
int size = nums.length;
for (int i = index; i < size; i++){
if(i < (size-1)
nums[i]= nums[i+1];
else
nums[i] = 0; //set to some base case or zero
}
}
}
You will not be able to "delete" the last value, but instead have to set it to some base case. If you want to truly delete i. you should use another data structure, ie ArrayList

Categories

Resources