Search for a number in an array java - java

I have code that first generates the array with 100 elements, then places randomly generated numbers in each element. I am trying to do a search for a number and if found, print out its index. the code I have so far is:
import java.util.Scanner;
public class Lab01
{
public static void main(String[] args)
{
int[] nums = new int[100];
for (int i = 0; i < nums.length; i++)
{
nums[i] = (int)((Math.random() * 100) + 1);
System.out.print(nums[i] + " , ");
}
System.out.println();
Scanner input = new Scanner(System.in);
int num;
System.out.println("What number would you like to search for?");
num = input.nextInt();
boolean found = false;
for (int i = 0; i < nums.length; i++)
{
if (num == nums[i])
{
found = true;
break;
}
if (found)
{
System.out.println("That number was found at index" + i);
break;
}
else
{
System.out.println("That number was not found.");
break;
}
}
}
}
I put in the print statements to see the values, so I could verify that it was working, but it ALWAYS returns "Not found". What am I missing here?

Try to replace this block, see the explanation in the bottom :
for (int i = 0; i < nums.length; i++)
{
if (num == nums[i])
{
found = true;
break;
}
if (found)
{
System.out.println("That number was found at index" + i);
break;
}
else
{
System.out.println("That number was not found.");
break;
}
With:
int i; // create this
for ( i = 0; i < nums.length; i++) // and remove int from for loop
{
if (num == nums[i])
{
found = true;
break;
}
}
if (found)
{
System.out.println("That number was found at index " + i);
}
else
{
System.out.println("That number was not found.");
}
Explanation:
Put out of for loop the both if condtion and remove the break statement from them and create a int i = 0 before the for loop like above.

You are breaking out of the loop after checking the first number, so if the first number doesn't match, you print "That number was not found". If the first number does match, you break without printing anything. You should only print "That number was not found" after checking all the numbers of the array.
Your if statement should come after the for loop, not inside it.
int i = 0;
for (; i < nums.length; i++) {
if (num == nums[i]) {
found = true;
break;
}
}
if (found) {
System.out.println("That number was found at index" + i);
} else {
System.out.println("That number was not found.");
}

Try this :)
public static void main(String[] args) {
int[] tab = {3, 2, 1, 7, 2, 1};
int userInput, i;
Integer index = null;
boolean found = false;
int counter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
userInput = input.nextInt();
for (i = 0; i<tab.length; i++) {
if (tab[i] == userInput) {
found = true;
index = i;
counter++;
}
}
if (found == true) {
System.out.println("Found number: " + userInput + " at index " + index + " and number is found " + counter + " times in array");
} else {
System.out.println("Not found number: " + userInput);
}
}

public class Contains {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
int toFind = 3;
boolean found = false;
for (int n : num) {
if (n == toFind) {
found = true;
break;
}
}
if(found)
System.out.println(toFind + " is found.");
else
System.out.println(toFind + " is not found.");
}
}

Related

Java: How to use binary search with an array

For this java program, I'm trying to use a binary search for the array I have created in the Class Numbers, however, when I enter the 4th choice, the program just ends. The method binSearch is in Class Numbers. I can enter the required the size of the array, generate random numbers, search for specific numbers, and display them. However, when I want to use a binary search, the program ends as previously said. What is the reason why the program ends and what needs to be done to fix that certain method?
public class Numbers {
int[] array;
private int sizeOfArray;
public Numbers() {
sizeOfArray = 0;
array= new int [sizeOfArray];
}
public Numbers(int sizeOfArray) {
this.sizeOfArray = sizeOfArray;
array= new int [sizeOfArray];
}
public void generateNumbers() {
Random randomNumber = new Random();
int theNumber = 0;
for (int i = 0; i < sizeOfArray; i++) {
theNumber = randomNumber.nextInt(50);
array[i] = theNumber;
}
}
public int count(int num) {
int theNumbers = 0;
for (int i = 0; i < sizeOfArray; i++) {
if (array[i] == num) {
theNumbers++;
}
}
return theNumbers;
} // end count method
public String toString() {
String myArray = "";
for (int i = 0; i < sizeOfArray; i++) {
myArray += array[i] + " ";
}
return myArray;
}
public int binSearch(int[] array, int key) {
int low = 0;
int high = sizeOfArray - 1;
//int middle = (low + high + 1) /2;
int location = -1;
while (high >= low) {
int middle1 = (low + high) / 2;
if (array[middle1] == key ) {
//return true;
}
if (array[middle1] < key) {
low = middle1 + 1;
}
if (array[middle1] > key) {
high = middle1 - 1;
}
}
//return false;
return location;
}
}
and here is the main menu:
boolean isDone = false;
String input = null;
Numbers theNumber = new Numbers();
Scanner scanner = new Scanner (System.in);
try {
while (isDone == false) {
/*Menu options */
System.out.println("Enter 1 to create array size");
System.out.println("Enter 2 to generate random numbers");
System.out.println("Enter 3 to search and display number of occurrences");
System.out.println("Enter 4 to binary search to find whether specific number exists");
System.out.println("Enter 5 to display the array");
System.out.println("Enter 6 to quit the program");
input = scanner.nextLine();
switch (input) {
case "1":
int intNumber1 = 0;
System.out.println("Enter required size:");
intNumber1 = Integer.valueOf(scanner.nextLine());
theNumber = new Numbers(intNumber1);
System.out.println("Array has been generated.");
break;
case "2":
//theNumber = new Numbers();
theNumber.generateNumbers();
System.out.println("Numbers have been generated and stored.");
break;
case "3":
int intNumber2 = 0;
System.out.println("Enter number to search for: ");
intNumber2 = Integer.valueOf(scanner.nextLine());
System.out.println("Number of occurences of " + intNumber2 + " in the array is " + theNumber.count(intNumber2) + ".");
break;
case "4":
int key = 0;
theNumber.binSearch(null, key);
System.out.println("Array is sorted: ");
break;
case "5":
int theNumbers = 0;
if (theNumbers == 0)
{
System.out.println("No array has not been generated yet.");
}
else
{
System.out.println("The numbers are: ");
}
System.out.println(theNumber.toString());
break;
case "6":
isDone = true;
System.out.println("Bye... See you again");
scanner.close();
break;
default:
System.out.println("These are invalid choices...please reenter.");
break;
}
}
}
catch (Exception exception)
{
System.out.println("This is an invalid choice...please reenter.");
scanner.nextLine();
return;
}

Trouble assigning a variable to display the index of an array

I am writing a program where I generate 100 random numbers, I prompt the user to enter a number, and the program says the number was found at index XX. Or that the number was not found. Here is what I have:
import java.util.*;
import java.util.Random;
public class lab1
{
public static void main (String[]args)
{
//Let's create an array with 100 random numbers
int [] randomArray = new int [100];
Random randomGenerator = new Random();
for(int i = 0; i < randomArray.length; i++)
{
randomArray[i] = randomGenerator.nextInt(100) + 1;
}
//ask user to enter a number between 1 and 100
Scanner input = new Scanner(System.in);
int searchNumber;
System.out.println("Please enter a number between 1 and 100 to search
for: ");
searchNumber = input.nextInt();
boolean found = false;
for(int i = 0; i < randomArray.length; i++)
{
if(searchNumber == randomArray[i])
{
found = true;
break;//Exits the loop
}
}
if(found)
{
System.out.println("We have found your number, " + searchNumber + "
at index " + index);
}
else
{
System.out.println("We did not find your number");
}
}
}
I am not able to get the index to display when my program finds a number, I know this is because the variable "i" is only defined within the for loop. I am not sure how to create a new variable outside of the for loop and assign i to that variable inside the for loop.
declare i outside the loop i.e.
int i;
for(i = 0; i < randomArray.length; i++)
{
...
...
...
}
then you can use the index i within your println.
if(found)
{
System.out.println("We have found your number, " + searchNumber + "at index " + i);
}
else
{
System.out.println("We did not find your number");
}
You had the right idea all along, and even articulated it perfectly: "...create a new variable outside of the for loop and assign i to that variable inside the for loop":
int foundAt = -1;
for(int i = 0; i < randomArray.length; i++)
{
if(searchNumber == randomArray[i])
{
foundAt = i;
break;//Exits the loop
}
}
if(foundAt != -1)
{
System.out.println("We have found your number, " + searchNumber + "
at index " + foundAt);
}
else
{
System.out.println("We did not find your number");
}
}

Why is my code not incrementing?

So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));

How to return a string?

import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.
In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...
You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();

Java skipping a number in the sequence

This is very interesting, i notice. Before i can explain further its best i show the code and you will understand what i mean.
This is the code:
public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];
public static void main(String[] args) {
addaccount();
}
public static void addAccount() {
int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);
while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}
if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));
}
}
while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}
private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}
So now that you have seen the code the problem that is hard to notice is this, take note of the line in the addaccount() method where
System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));
this line the first check+1 will give me 1 then the next one gives me 3! and then the next time i run the method it gives me 4 and then again 5 and so on so forth, what is happening to 2?
You have that println in an else block, and when j == 1 you're hitting the else if case. Try removing this line
accnums[1] = new Integer (1);

Categories