Java - Searching an element in a random array - java

I executed the following code:
import java.util.Scanner;
public class Linear_Search {
public static void main(String[] args) {
int arr[] = new int[20];
for(int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 10) + 1;
}
System.out.print("Array is: ");
for(int i : arr)
System.out.print(arr[i] + " ");
//int arr[]= {1,2,4,5,6,7,8,43,6,4,2,6,8,3};
System.out.println();
System.out.println("Enter the number you want to search");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean found = false;
String indices = "";
for(int i = 0; i < arr.length; i++) {
if(num == arr[i]) {
found = true;
indices = indices + i + ", ";
}
}
if(found == false) {
System.out.println(num + " does not exist");
}
else {
System.out.println(num + " found at index: " + indices.substring(0, indices.length() - 2));
}
sc.close();
}
}
Output:
Array is: 3 3 1 2 8 1 2 2 3 1 3 3 7 1 7 3 1 3 8 3
Enter the number you want to search
2
2 found at index: 0, 1, 8 ,15
Why is this displaying random indices as answers. The code works fine when i use a custom array like the one that is commented in the code. Is it related to explicit cast on Math.random() or something else?

You are mislead by the loop printing the array, which doesn't really print the array elements.
Change:
for(int i : arr)
System.out.print(arr[i] + " ");
to:
for(int i : arr)
System.out.print(i + " ");
and you'll see the actual array values.
When you iterate over an array with the enhanced for loop, you are iterating over the array values not over the array indices.

Related

How to show only occurrences of numbers user input in java?

I'm new to programing and trying to solve this problem, but have no idea what I did wrong.
The program is supposed to take user input until 0 is entered and after that, print out information of occurrences of numbers user input - and here is my problem.
The program I wrote shows occurrences of all numbers (up to max number that can be input), not only those that user wrote.
My code:
package numbers;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] occurences = new int[11];
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
for (int i = 0; i < 11; i++) {
System.out.print("Value: " + i + " Occurences: " + occurences[i] + " ");
}
}
}
Use if statement to print only numbers with occurences higher than 0.
Side notes:
Array values initialization is not needed:
for (int i = 0; i < 11; i++) {
occurences[i] = 0;
}
Value at each index is already 0, check this question.
While loop condition, does not make much sense
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
Array size is 11, meaning indexes range from 0 to 10 inclusive. Since you allow input 11, you will get ArrayIndexOutOfBoundsException.
You can make use of map.
Map<Integer, Integer> occ = new HashMap<>();
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occ.put(num, occ.getOrDefault(num, 0)+1);
num = scan.nextInt();
}
for(int i : occ.keySet()){
System.out.print("Value: " + i + " Occurences: " + occ.get(i) + " ");
}

Java, removing duplicate output from separate lines generated by nested for loops

I am new to java, and I have this program that takes a number between 1 and 10 from a user and displays the multiplication table for that number. Here is the code:
import java.util.Scanner; //importing the scanner library
public class question3 {
public static void main(String[] args){
Scanner keyb = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 10: ");
int userNumber = keyb.nextInt();
while (userNumber <= 0 || userNumber >= 10){
System.out.print("Enter an integer between 1 and 10: ");
userNumber = keyb.nextInt();
}
keyb.close();
for (int counter = 1; counter <= userNumber; counter++){
System.out.print(counter + "\t");
for (int number = 2; number <= userNumber; number++){
System.out.print((counter * number) + "\t");
}
System.out.println(" ");
}
}
}
So if the user enters 4, the output will look like:
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
This works. I need to take the multiplication table and remove any duplicate numbers. So if the user enters 4, the desired output will look like:
1 2 3 4
4 6 8
9 12
16
How can I remove the duplicate output when it only exists in the for loop print statements?
Thanks!
Set<Integer> generatedNumbers = new HashSet<>();
for(int counter = 1; counter <= userNumber; counter+=1)
{
System.out.print((generatedNumbers.contains(counter) ? "" : counter) + "\t");
generatedNumbers.add(counter);
for(int number = 2; number <= userNumber; number+=1)
{
int product = number * counter;
System.out.print((generatedNumbers.contains(product) ? "" : product) + "\t");
generatedNumbers.add(product);
}
System.out.println();
}
You need an extra List<Integer> to check the condition only: (Just need to align the space(DIY))
public class question3 {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 10: ");
int userNumber = keyb.nextInt();
while (userNumber <= 0 || userNumber >= 10) {
System.out.print("Enter an integer between 1 and 10: ");
userNumber = keyb.nextInt();
}
keyb.close();
List<Integer> arr = new ArrayList<Integer>();
for (int counter = 1; counter <= userNumber; counter++) {
if (!arr.contains(counter)) {
System.out.print(counter + "\t");
arr.add(counter);
} else
System.out.println("\t");
for (int number = 2; number <= userNumber; number++) {
if (!arr.contains((counter * number))) {
System.out.print((counter * number) + "\t");
arr.add((counter * number));
} else {
System.out.print("\t");
}
}
System.out.println("\t");
}
}
}
EDIT:
Also utilize do-while loop here to avoid duplicate code to ask input like
System.out.print("Enter an integer between 1 and 10: ");
int userNumber = keyb.nextInt();

How to make this programm to count the odd and even numbers in an array?(eclipse)

Thanks for the answers guys, didn't expect getting answers so fast.
Ok so in this code at the final stage it is meant to count how many odd and evens numbers there are in the array length you decide.
If you for example type in 10 it prints out 10 random numbers between the intervall of 0-999 and then it seperates the odd and even numbers
In the last stage it's meant to calculate how many odd and even numbers there are like ''out of the 10 numbers 4 of them were even numbers and 6 were odd numbers''
Right now in the last stage it just prints out numbers randomly and doesen't calculate how many odd and even numbers there are. I don't know how to fix it.
I have ran out of ideas about it so hopefully someone here can make it work properly.
import java.util.Scanner;
public class Uppgift4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length;
while (true)
{
System.out.print(" \n\nHow many numbers do you want in the intervall 0-999?(turn off with -1 or 1000):");
length = scan.nextInt();
if (length>999)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
if (length<0)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
System.out.println("\n Here are the random numbers:");
int [] ar1 = new int[length];
for(int i = 0; i < length; i++) {
ar1[i] = (int)(Math.random() * 1000);
{
System.out.print(" "+ar1[i]);
}
}
System.out.println(" \n");
System.out.println(" Here are the numbers divided between even and odd numbers:");
System.out.print(" ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.print("- ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 != 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.println(" \n");
System.out.print(" Of the above numbers "+ length + " so ");
System.out.print("where ");
for(int evennumbers = 1 ; evennumbers < length ; evennumbers++)
{
if(ar1[evennumbers] % 2 == 0)
{
System.out.print(evennumbers+" ");
}
}
System.out.print(" of the numbers even and odd numbers were ");
for(int oddnumbers = 1 ; oddnumbers < length ; oddnumbers++)
{
if(ar1[oddnumbers] % 2 != 0)
{
System.out.print(oddnumbers+" ");
}
}
}
}
You need to count the number of even and odd number:
int even = 0;
int odd = 0;
// Loop through the final array
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
even++;
} else {
odd++;
}
}
Even simpler:
for(int i = 0 ; i < length ; i++)
{
odd += (ar1[i] % 2)
}
even = length - odd;
just make two global variables to count the odd and even and put them into the condition where you are checking for odd and even.
code
Why not just make use of bitwise AND and remove those conditionals like so:
int odd = 0;
int even = 0;
for(int i=0;i<length;i++){
odd+=ar1[i]&1;
even+=((ar1[i]+1)&1);
}
you can use this way , very simple
public static void main(String []args){
Integer[] arr = new Integer[] { 1,2,3,4,5};
int oddCount =0; int evenCount=0;
for ( int i=0; i< arr.length ;i++){
if( ( arr[i] % 2) == 0 )
evenCount++;
if( arr[i] % 2 != 0 )
oddCount++;
}
System.out.println( "oddCount in Array :" + oddCount + " EvenCount in Array : " + evenCount);
}

For loop printing an unexpected number of times

public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.print("Please enter five numbers. \na=");
array[0] = input.nextInt();
System.out.print("\nb=");
array[1] = input.nextInt();
System.out.print("\nc=");
array[2] = input.nextInt();
System.out.print("\nd=");
array[3] = input.nextInt();
System.out.print("\ne=");
array[4] = input.nextInt();
boolean totalIsZero = false;
for (int i=0;i<array.length ;i++) {
for (int j=1;i>j ;j++ ) {
if ((array[i] + array[j])==0) {
System.out.println("The numbers " + array[i] + " and " + array[j] + " have a total sum equal to 0.");
totalIsZero = true;
}
}
}
if (!totalIsZero) {
System.out.print("None of the numbers have a total sum of 0 with each other. ");
}
}
Here is some simple code I just wrote. Its task is to check if the sum between every two numbers in an array (consisting of five numbers) is equal to zero.
The problem I have is that when there are two pairs of numbers, both equal to 0, at the end of the program there is a message for one of the pairs only, not for both, as I expected.
How can I fix that, so the user can read that there are two pairs of numbers equal to 0?
Not sure if this will work perfectly because I haven't tested it and I haven't used java in a while, but just create the array the same way you do it in your post, but try the rest for the actual bulk of the function.
// various input calls above^ to create array
int count = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = i + 1; j < array.length; j++)
{
if(array[i] + array[j] == 0)
{
System.out.println("The numbers " + array[i] + " and " +
array[j] +
" have a sum equal to zero.");
count++;
}
}
}
if(count == 0)
{
System.out.println("No sum between any numbers is equal to 0");
}

How to return a single print statement from a search() method in an array?

I'm having trouble with my search method. What I want to do is have my search method print the statement only once. So if my array contains "3" more than once, I only want to print "3 was found." once instead of checking each value and reporting that there is or is not a "3" at that point in the array. How would I do that?
To clarify, this is what I have:
`0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was found.
2 was not found.
2 was not found.`
And this is what I want:
0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was found.
2 was not found.
So this is my complete class. I created a method called initialize that will assign each element in my array a random integer between 0 and 10; a method called print to print out the contents of my array; a method called printStats to find and then print the average, maximum, and minimum value in my array; and a method called search that searches my array (and prints the result) for an integer parameter passed to my method.
Everything works correctly.
public class ArrayLab
{
private int[] array;
public ArrayLab(int numElements)
{
array = new int[numElements];
}
public void initialize()
{
array[0] = (int) (Math.random()*11);
array[1] = (int) (Math.random()*11);
array[2] = (int) (Math.random()*11);
array[3] = (int) (Math.random()*11);
array[4] = (int) (Math.random()*11);
array[5] = (int) (Math.random()*11);
array[6] = (int) (Math.random()*11);
array[7] = (int) (Math.random()*11);
array[8] = (int) (Math.random()*11);
array[9] = (int) (Math.random()*11);
}
public void print() {
System.out.println(array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "," + array[4] + "," + array[5] + "," + array[6] + "," + array[7] + "," + array[8] + "," + array[9]);
System.out.println();
}
public void printStats()
{
double sum = 0;
int max = 0;
int min = 0;
min = array[0];
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
double average = sum/array.length;
System.out.println("Average Value: " + average);
System.out.println("Maximum Value: " + max);
System.out.println("Minimum Value: " + min);
}
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
}
else
{
System.out.println(numChosen + " was not found.");
}
}
}
}
Start using return or break statement to break the loop after you hit the first successful search.
Also, you should not print the Was Not Found every time while iterating the array. You should print it only once in the end when your array gets exhausted completely and search query is not found.
Here is the modified code snippet:
boolean flag = false;
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
flag = true;
break;
}
}
if(!flag) {
System.out.println(numChosen + " was not found.");
}
Alternatively, you can also do the following:
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
Well, you don't need to keep iterating through the loop once you found the number. Also, you want to print "was not found" in a case it didn't find anything, meaning the loop finished without printing anything yet.
So this is how you should implement it:
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
}
In a case it found something, it will print the message and exit the method and never reach the printing of second message. It will only print the second message when the loop is over.
You are displaying results in your public void search(int numChosen) function. In your case, instead of printing every time you encounter a match, put a counter instead, then print once: that counter with the rest of you sentence.
Try this:
public void search(int numChosen)
{
int count = 0;
for (int i = 0; i < array.length; i++)
if (array[i] == numChosen)
count++;
if (count == 0)
System.out.println(numChosen + " was not found.");
else
System.out.println(numChosen + " was found " + count + " times.");
}

Categories