Search an Array for a user input - java

I am trying to finish an assignment. I have to write a program in Java that generates random numbers in an array size100 and then asks the user for a number between 1 and 100. If the number is in the array it displays that the number was found at what location. If not it kicks back that no number was found. So far I can only get it to kick back that the number was not found. It prints it back out 4 different times.
package lab1;
import java.util.Random;
import java.util.Scanner;
public class RandomArray {
public static void main(String[] args) {
int [] randomArray = new int [100];
Random randomGenerator = new Random();
for (int i = 0; i< randomArray.length; i++){
randomArray[i] = randomGenerator.nextInt(100);
}
Scanner input = new Scanner (System.in);
int searchNumber;
System.out.println("Please enter a number to search for between 1 and 100: ");
searchNumber= input.nextInt();
boolean found = false;
for (int i = 0; i < randomArray.length; i++){
if (searchNumber == randomArray[i]){
found = true;
break;
}
if (found){
System.out.println("We have found your" + "number at index " + i);
}else{
System.out.println("We did not find your number");
}
}
}
}

Your if statement inside for loop. So each time searchNumber == randomArray[i] is false you checkif (found). It leads to else branch which print"We did not find your number"`.
PS: Learn how to use debugger. It greatly simplify your life.

you forget the case , if there are more than two location of the same number, as it is just generating random number.
How about this :
boolean found = false;
for (int i=0; i < randomArray.length; i++) {
if (searchNumber == randomArray[i]) {
found = true;
System.out.println("We have found your number at index " + i);
}
}
if (!found) {
System.out.println("We did not find your number");
}

Related

How to create random.txt file then randomly 500 random integers in the file then use that file to run common algorithms on them?

The code given below is not working:
My tasks are to,
Write a program that generates 500 Random Integers and stores them into an array. Integer values will be between 1 - 1000.
Print the 500 Random Integers to .txt file
The main method will control the run of the program. (menu, etc.)
Create a menu using the if/else ladder or switch case to control the operation of the program. The menu should be in main.
Create a “programmer created class” called Common_Algo
Read the 500 Random Integers from th .txt file you created in Task
2:
Use the class constructor to fill the array with random integers from the .txt file. The 500 integer array (arr[500]) will be an instance variable in the “programmer created class” - Common_Algo
All methods below will be encapsulated together with the 500 integer array in the Common_Algo class.
The main method from outside the Common_Algo class will control the
operation of the program.
Implement methods to achieve each outcome given below.
(Your menu will call the methods. All methods will operate on the same Array.)
Enter 1. Output all values
Enter 2. Output Sum of All Values and the Mean Average of Values
Enter 3. Output all odd numbers
Enter 4. Output all even numbers\
Enter 5. Output Middle Values (Values in the Middle)
Enter 6. Output First Value in the Array
Enter 7. Output Last Value in the Array
Enter 8. Enter a Search Value
Enter 9. Output Sorted Array
Enter 10. Output the Highest Value and its location in the array.
Enter 11: Output Lowest Value and its location in the array.
Enter 12: Exit
**Following is what I have implemented so far but it does not compile on the command prompt.**
import java.io.*;
import java.util.*;
public class Common_Algo
{
private int i;
int [] arr;
public Common_Algo()
{
try {
FileReader file = new FileReader("random.txt");
Scanner scanner = new Scanner(file);
arr = new int [500];
i = 0;
while (scanner.hasNextInt())
{
arr[i++] = scanner.nextInt();
}
}
catch (Exception e)
{
System.out.println(e);
}
}
void printAllValues()
{
for (i = 0; i<500; i++)
{
System.out.println(arr[i]);
}
}
void sumAndMean()
{
// calculate the sum
int sum = 0;
float average = 0;
for (int i = 0; i< arr.length; i++){
sum = sum + arr[i];
}
System.out.println("The sum of all the elements in the array " + sum);
// calculate the average
average = sum/arr.length;
System.out.println("Average of all vlaues of an array:" + average);
}
void oddNumber()
{
System.out.println("Odd numbers in array is:");
for(int i = 0; i<arr.length; i++)
{
if (arr[i]%2 ==0)
{
System.out.println(arr[i]);
}
}
}
void evenNumber()
{
System.out.println("Even numbers in array is:");
for(int i=0; i<arr.length; i++)
{
if (arr[i]%2==0)
{
System.out.println(arr[i]);
}
}
}
void middleValue(){
int m = 0;
if (arr.length%2 == 1)
{
m=(arr[(arr.length + 1)/2-1]);
}
else
{
m=(arr[arr.length/2-1]+arr[arr.length/2])/2;
}
System.out.println("Middle Value = "+ m);
}
void firstValue(){
System.out.println("The first value in the array is: " + arr[0]);
}
void lastValue()
{
System.out.println("The last value in the array is: " +arr[arr.length-1]);
}
void searchValue()
{
Scanner scanner = new Scanner (System.in);
int search_Value,flag=0;
System.out.println("Enter search value: ");
search_Value = scanner.nextInt();
//this does linear search for searching the value in array
for (int i = 0; i<arr.length; i++)
{
if (search_Value == arr[i])
{
System.out.println("Value " + search_Value +" is found at location "+ i);
flag = 1;
}
}
if (flag == 0)
{
System.out.println("Value " + search_Value + " is not found inside the array");
}
}
void sortArray()
{
Arrays.sort(arr);
System.out.println("The sort array list: ");
//sort array list
for (i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
void highValue()
{
int max = arr [0];
for (int i = 1; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
System.out.println("The highest value of array is: " + max);
}
}
}
void lowValue()
{
int min = arr[0];
for (int i = 1; i <arr.length; i++)
if (arr[i] < min)
min = arr[i];
System.out.println("The lowest value in the array: " + min);
}
}
class RandomData
{
public static void main(String[] args) {
int i,choice;
Scanner scanner = new Scanner(System.in);
Random rnum = new Random();
try {
PrintWriter fileout = new PrintWriter(new FileWriter ("random.txt"));
for (i = 0; i<500; i++)
{
fileout.println(rnum.nextInt(1000));
}
fileout.close();
}
catch (Exception e)
{
System.out.println(e);
}
Common_Algo object = new Common_Algo();
do
{
System.out.println("Enter 1 for: Output of all values ");
System.out.println("Enter 2 for: Ouput of Sum and mean Average values");
System.out.println("Enter 3 for: Output of all odd numbers");
System.out.println("Enter 4 for: Output of all even numbers" );
System.out.println("Enter 5 for: Output of middle values");
System.out.println("Enter 6 for: Output of first value in the array");
System.out.println("Enter 7 for: Output of last vlaue in the array");
System.out.println("Enter 8 for: Output of the entered search value");
System.out.println("Enter 9 for: Output of the Sorted Array");
System.out.println("Enter 10 for: Output of the highest value and its location in the array");
System.out.println("Enter 11 for: Output of lowest value and its location in the array");
System.out.println("Enter 12 for: Exit");
System.out.println("Please enter your choice");
choice = scanner.nextInt();
switch(choice)
{
case 1:
object.printAllValues();
break;
case 2:
object.sumAndMean();
break;
case 3:
object.oddNumber();
break;
case 4:
object.evenNumber();
break;
case 5:
object.middleValue();
break;
case 6:
object.firstValue();
break;
case 7:
object.lastValue();
break;
case 8:
object.searchValue();
break;
case 9:
object.sortArray();
break;
case 10:
object.highValue();
break;
case 11:
object.lowValue();
break;
case 12:
System.exit(0);
}
}
while(choice!=12);
}
}
Do not try to do everything at once in one big jump. Do it step by step. Your instructor has kindly already broken the problem up into steps. Write code for each step separately. Test that code to make sure it works, fixing any errors you find. Yes, this does mean reading and understanding any compile errors you find. Because you are only writing one piece at a time, there should not be too many errors in each piece.
When you have a tested and working piece of code, integrate it with the other pieces you have written so far and test the new combined code. Again, fix all errors.
This stepwise approach means you never have a big blob of code to fix, just small pieces which are a lot easier to work with. You build your final program piece by piece, testing and fixing all the way.

Bingo game Java

I'm trying to write a java code with(bingo game),(bullseye game)
the rules are simple:
computer picks 4 numbers
user input 4 numbers
must check the user input is between 1 to 10
If the user input exists in the computer randomized numbers it will be 1 bulls
If a number exist in the same location of the computer randomized number it will show 1 "eye"
Max limit is 20 tries until the user is considered "failed"; I need to print each round how many bulls were and how many eye were by the user input;
Example:
if the pc randomizing 1 4 6 7
and the user type 3 4 1 7
the output will be 3 bulls and 2 eyes.
my code prints 0 and 0 at the end.
Thanks for the help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
int[] pcGuess = new int[4];
int[] playerGuess = new int[4];
int countGuess = 0, bulls = 0, eye = 0;
final int maxGuess = 20;
System.out.println("Please press enter to begin");
in.nextLine();
boolean areNumbersCorrect = true; // a boolean value to define if the user input are correct (values between 1 to 10)
for (; countGuess < maxGuess; countGuess++) {
System.out.println("Please enter 4 numbers between 1-10");
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = in.nextInt();
pcGuess[i] = r.nextInt(10)+1;
if (playerGuess[i] < 0 || playerGuess[i] > 10) { // an if statement to check if the user input are correct
areNumbersCorrect = false;
do { // do while loop if the boolean is not true. (force the user to enter correct values)
System.out.println("Please try again");
for (int j = 0; j < playerGuess.length; j++) {
playerGuess[j] = in.nextInt();
if (playerGuess[j] > 0 && playerGuess[j] < 10) {
areNumbersCorrect = true;
continue;
}
}
} while (!areNumbersCorrect); // end of do while loop
}
for (int j=pcGuess.length; j>0; j--) { // for loop to check each number from the user and computer.
if (playerGuess[i] == pcGuess[i]) {
eye++; // if the user number exist in the same location evaluate eye++
if (playerGuess[i]%pcGuess[j]== 0) {
bulls++; // if the user number exist in the randomized number but not in the same location evaluate bulls++
}
}
}
System.out.println(
eye+" Hits!(same pc number and location)"+" And: "+bulls+" Numbers exist");
} if(eye==4&&bulls==4) {
break;
}
}
System.out.println("It took you: "+countGuess+" Times to guess the numbers");
}
}
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
ArrayList<Integer> randNumbers = new ArrayList<>();
Random random = new Random();
String input;
int number;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please press enter to begin");
input = sc.nextLine();
}while (!input.equals(""));//loop while user doesn't press ENTER
for (int i = 0; i < 4; i++){
randNumbers.add(random.nextInt(10) + 1);//loop to fill the randNumbers arraylist with random numbers
}
/*
randNumbers.add(3);
randNumbers.add(2);
randNumbers.add(9);
randNumbers.add(9);
*/
System.out.println("My random numbers: " + randNumbers.toString());
int counter = 0;
int bulls = 0;
int eyes = 0;
do {
System.out.println("Please enter 4 numbers between 1-10");
number = sc.nextInt();
if (number > 0 && number <= 10){
//System.out.println("index of rand: " + randNumbers.indexOf(number));
//System.out.println("count: " + counter);
if (randNumbers.indexOf(number) == counter){
eyes++;
System.out.println("eyes++");
}else if (randNumbers.contains(number)){
bulls++;
System.out.println("bulls++");
}
counter++;
System.out.println("Number " + counter + " introduced. " + (4 - counter) + " more to go.");
}else {
System.out.println("Wrong number.");
}
}while (counter < 4);//loop for user to introduce valid numbers
System.out.println("You scored " + bulls + " bulls and " + eyes + " eyes.");
}
}
Try this piece of code. Note that I used ArrayList rather than an array, as it offers methods such as .contains() and .indexof().
WARNING: Code will fail if the randNumbers arraylist contains two numbers that are equals, such as the 3-2-9-9 array that is commented when you input 9-9-9-9 as your number guesses. This is because .indexof() method:
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
Meaning the code fails to account the last 9 as it will compare the count index (3) to the first occurrence of 9 in the randNumbers, which is 2, making it false and not increasing eyes count.
Since I'm short on time, and this is an assigment you have and just copying it won't teach you much, I'll leave it to you to solve this specific case (I already told you what's wrong, won't be difficult to solve).

Using arrays to store primes

Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}

Validate multiple inputs to an array in java

I have a HOMEWORK assignment that involves users inputs.
I want to ask the user for three integer inputs in the range 1-7 and store them in an array.
What I have so far seems to validate properly if all inputs are over 7 and rules out strings etc inputs and but still allows for a single input to be over 7.
Any help is appreciated.
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
while(!valid)
{
System.out.println("enter three numbers: ");
if(in.hasNextInt())
{
for(int i = 0; i< inputRange.length; i++)
{
inputRange[i] = in.nextInt();
if(inputRange[i] >= 1 && inputRange[i] <= 9){
valid = true;
}
}
}else{
in.next();
}
}
Your logic is fine, but you need to restart valid to false again each time user is going to enter a new digit.
Here's how you can validate user input to be between 1-9 with a do-while using your same logic just a little bit different.
Also next time be sure to post a valid MCVE and not just "snippets" (it should include a main method and imports)
import java.util.Scanner;
public class ValidationOfNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
int counter = 0;
int number = 0;
System.out.println("Enter 3 digits between 1-9"); //Ask for digits, numbers can have multiple digits, while digits are numbers from 0-9
for (int i = 0; i < inputRange.length; i++) {
valid = false; //Restart "valid" variable for each new user input
do {
number = in.nextInt();
if (number >= 1 && number <= 9) {
valid = true; //If valid, it will exit do-while
} else {
System.out.println("Enter a valid digit between 1-9");
}
} while (!valid);
inputRange[i] = number; //We know it's valid because it went out of do-while, so we can now store it in the array
}
for (int i = 0; i < inputRange.length; i++) {
System.out.println(inputRange[i]);
}
}
}
Here is the code
Scanner in = new Scanner(System.in);
int count = 0;
int data[] = new int[3];
while(count < 3) {
if(in.hasNextInt()) {
int val = in.nextInt();
if(val>=1 && val <=7) {
data[count] = val;
count++;
}
}
else {
in.next();
}
}

Java - No Duplicate number array

I am in the process of creating of a Lottery Program using Java via BlueJ and I am having trouble with the user inputted numbers and the number being generated by the program (up to and including 1-49), I need the numbers that are entered by the user to not be duplicate i.e. the user cannot enter 1 and 1.
I am not really sure how to get the numbers to not be duplicate i was thinking of using an Array but im not sure what type or where to begin im rather new to the whole programming thing.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class JavaApplication8 {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
Scanner keyIn = new Scanner(System.in);
int[] LotteryNumbers = new int[6];
int input;
int count = 0;
System.out.print("Welcome to my lottery program which takes\nyour lottery numbers and compares\nthem to this weeks lottery numbers!");
System.out.print("\n\nPress the enter key to continue");
keyIn.nextLine();
for (int i = 0; i < LotteryNumbers.length; i++)
{
count ++;
System.out.println("Enter your five Lottery Numbers now " + count + " (must be between 1 and 49): ");
input = Integer.parseInt(user_input.next());
if (input < 1 || input > 49)
{
while (input < 1 || input > 49)
{
System.out.println("Invalid number entered! \nPlease enter lottery number (between 1 and 49) " + count);
input = Integer.parseInt(user_input.next());
if (input >= 1 || input <= 49)
{
LotteryNumbers[i] = input;
}
}
}
else
{
LotteryNumbers[i] = input;
}
}
System.out.println("Thank you for your numbers.\nThe system will now check if you have any matching numbers");
System.out.print("Press the enter key to continue");
keyIn.nextLine();
Random randNumGenerator = new Random();
StringBuilder output = new StringBuilder();
int[] ActLotteryNumbers = new int[6];
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
int roll = randNumGenerator.nextInt(49);
ActLotteryNumbers[j] = roll;
}
System.out.println(Arrays.toString(ActLotteryNumbers));
int counter = 0;
for (int i = 0; i < LotteryNumbers.length; i++)
{
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
if (LotteryNumbers[i] == ActLotteryNumbers [j])
{
counter ++;
System.out.println("The numbers that match up are: \n" + LotteryNumbers[i]);
}
}
}
if (counter == 0)
{
System.out.println("You had no matching numbers this week ... Try Again next week!");
}
}
}
As "fge" mentioned, use Set to add all the values that you are getting from the user.
Get the user inputs and add it to Set.
Use a Iterator to check the user entered values and generated random numbers.
Set myset = new HashSet();
myset.add(user_input1);
myset.add(user_input1);
To retrive use the iterator'
Iterator iterator = myset.iterator();
while(iterator.hasNext(){
int value= iterator.next();
if(randomValue==value)
//do your logic here
}
I am assuming this is for a school project/lab? (This is due to the JavaApplication8 class name) If that is the case, what the instructor is most likely looking for is a contains method.
For a contains method you write a method that takes an integer and checks to see if it is already in your LotteryNumbers array and returns a boolean. It would return true if it is in the array, false if it is not in it. This method would be called before inserting the number into LotteryNumbers. You could use your count variable that doesn't appear to be used anywhere else as the limit on your loop in the contains method to avoid checking uninitialized entries.
If there is no restriction on type, the set idea suggested by others works and is more efficient, it just depends on what you are supposed to be using for your requirements.
Additionally, the logic you use should most likely be applied to ActLotteryNumbers as well. If you can't have duplicates incoming, you shouldn't have duplicate values in the comparing array. Lottery isn't fair in real life, but not that unfair ;-)
First step should be checking your restrictions on this project.

Categories