Print out the length of an array in JAVA - java

I need to program a lottery simulator and basically everything works fine but I have one small problem at the end of the problem. There are 2 Arrays(i need to work without Array Lists) which get compared. The generated winning numbers and the numbers entered by the user. I succeeded in showing what numbers are the right guesses. But what doesn't work is showing HOW MANY guesses were correct. I tried System.out.println("You guessed this many numbers right: "+intArray.length[i] but this didn't work. Is there any way to show the exact number of how many numbers were guessed right? Thanks for any help in advance
for (int i=0; i< intArray.length;i++){
for (int j=0; j< ownArray.length;j++){
if (intArray[i] == ownArray[j]){
System.out.println("Your following guess was correct: "+intArray[i]);

Just use a count variable
public static void main(String[] args) {
int[] intArray = {1,2,4,5};
int[] ownArray = {1,0,2,7};
int count = 0;
System.out.println("Your following guesses were correct: ");
for (int i = 0; i < intArray.length; i++){
for (int j = 0; j < ownArray.length; j++){
if (intArray[i] == ownArray[j]){
System.out.print(intArray[i] + " ");
count++;
}
}
}
System.out.println("\nNo. of correct guesses: " + count);
}
Output:
Your following guesses were correct:
1 2
No. of correct guesses: 2

This is actually quite simple to do if your lottery numbers are positive numbers. It is more involved if the numbers can be negative. The basic algorithm is to compare lottery numbers one by one against all the player's guesses repeatedly. If there is a match then we record -1 in the user guess array and increment a counter to track the number of correct entries.
Some code will make this clearer:
public class LotteryNumbers {
public static void main(String[] args) {
int[] lotteryNumbers = {1,2,3,4,5,6};
int[] userGuess = {1,2,3,4,8,9};
int correct = 0;
for(int i=0; i<lotteryNumbers.length; i++) {
for(int j=0; j<userGuess.length; j++) {
if( userGuess[j] == lotteryNumbers[i]) {
userGuess[j] = -1; // 'eliminate' this guess for checking
correct++;
break;
}
}
}
System.out.println("Number of correct numbers = " + correct);
}
}
Outputs:
Number of correct numbers = 4
This works because the algorithm strikes out matches in the player's guesses and guards against future matching next time through the loop. You can imagine that what we are actually doing is striking off numbers in the player's guess that match against the lottery numbers.

Related

How can I make the script that counts which number occurred most often and counts how many times do each of the 10 random numbers occur

To explain about the program that I am making, it is program that asks the user how many times he would like his coin to flip. In this program, the coin of the head is even, and the odd is the tail.
I created a script that randomizes numbers from 1 to 10 based on the number you entered. And also I've made the script that how many odd and even numbers had come out, but I don't know how to make a script that shows how many times do each of the 10 random numbers occur and which number occurred most often.
Here is the script that I have made:
import java.util.*;
public class GreatCoinFlipping {
public static void main(String[] args) {
System.out.println("How many times do you want to flip the coin? : ");
Scanner sc = new Scanner(System.in);
int amount = sc.nextInt();
int[] arrNum = new int[amount];
int even = 0, odd = 0;
for (int i = 0; i < amount ; i++) {
arrNum[i] = (int)(Math.random() * 10 + 1);
System.out.println(arrNum[i]);
if (arrNum[i] % 2 == 0) even++;
else odd++;
}//end for
System.out.println("Head: " + even + ", Tail: " + odd);
}//end main
}//end class
What I am expecting on this script that that I want to make the script that shows how many times do each of the 10 random numbers occur and which number occurred most often and I want to make it by the count method. But the ramdon number part has to be in array method. Can someone please help me with this problem?
The arrNum variable will contain an array of all occurences of each number. So if you want to count, for example, how many times 4 occurred in this, you can do this:
Arrays.stream(arrNum).filter(n -> n == 4).count()
For 7 you can do this:
Arrays.stream(arrNum).filter(n -> n == 7).count()
And you can do the same for other digits (1 to 10).
This would be a simple/straight-forward way of doing it. You can also improve it by creating a method that returns this count:
public static int getCount(int[] arr, int num) {
return Arrays.stream(arr).filter(n -> n == num).count();
}
And then call this in a loop:
for(int i=1; i<=10; i++) {
System.out.println("Count for " + i + ": " + getCount(arrNum, i));
}
To keep track of the random number you generate you can use a array. The array starts out as all 0's and is of size 10 (because there are 10 numbers between 0-9).
int size = 10;
int numbers_counter[] = new int[size];
// initialize the values
for(int i = 0; i < size; i++){
numbers_counter[i] = 0;
}
// count some random numbers
for(int i = 0; i < 100; i++){
numbers_counter[(int)(Math.random() * size)] += 1;
}
// print how many times each number accured
for(int i = 0; i < size; i++){
System.out.println("" + i + " occured: " + numbers_counter[i] + " times");
}
You can apply this method to your code.

Modification of Bubblesort program with user input

I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.

Read in 5 numbers from a user and compute the frequency of positive numbers entered

Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive integer");
int number = input.nextInt();
for(int i = -2 ; i < 4 ; i++)
System.out.println("Positive Count is: " + i);
}
}
Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!
for(int i=-2 ; i<4 ; i++)
System.out.println("Positive Count is: " +i);
Instead, do something like:
for (int loops = 0; loops < 5; loops++) {
int number = input.nextInt();
Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:
int loopCount = 5;
int numbers[] = new[loopCount];
for (int loops = 0; loops < loopCount; loops++) {
numbers[loops] = input.nextInt();
And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:
for (int number : numbers) {
if (number > 0) {
System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
}
with a little helper method:
private int computeFrequency(int number, int allNumbers[]) {
...
Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.
Try this one, Remember if you only want to know the frequency(not storing)
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
int i = 1;// is a counter for the loop
int positive =0;// counts positive numbers
while(i<=5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole positive number");
int number = input.nextInt();
if(number > 0){
positive ++;
}
i++;
}
System.out.println("Positive Count is: "+ positive);

How many tries to guess

I have a lottery program that I would like to ask me to take a guess at the 'winning' numbers and then will generate said numbers. When it's done, it will print those numbers back to me, and tell me how many tries it took to arrive at the correct answer.
My code is below. I thought I'd gotten the answer from another thread, was so sure that I closed it - and can't find it now. My question is really just a 'What's wrong with my code?' type, as I think that the code is working, but since the array is 6 numbers I figure it will take the computer some time.
For that reason, I changed the array to just 1 number and it was still taking forever to come back with a "You guessed it in...!" Leading me to believe there is something else wrong I'm missing.
package lottery;
import java.util.Scanner;
public class lottery { // Begin lottery class
public static void main(String[] args) { // Begin MAIN method
// Define variables
Scanner keyboard = new Scanner(System.in);
int[] lottery = new int[6];
int randomNum = 1 + (int) Math.random() * 59;
int noTimes = 1;
int guess = 0;
// End variable definition
System.out.println("Generating lottery numbers, what is your guess?");
while (guess != randomNum) {
guess = keyboard.nextInt();
guess++;
}
// Input received - generate numbers now
System.out.println("Thank you. Generating lottery numbers now...");
for (int i = 0; i < 6; i++) {
randomNum = (int) Math.ceil(Math.random() * 59); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) Math.ceil(Math.random() * 59);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int j = 0; j < noTimes; j++) {
for (int i = 0; i < lottery.length; i++) {
System.out.print("The winning numbers are: " + lottery[i] + " ");
}
System.out.println("\n");
System.out.print("You correctly guessed in " + guess + " tries.");
}
} // End MAIN method
} // End Lottery class
Apparently, I don't know how to do the regular code tag? colors?
There are various problems in your code, which are explained below.
To generate a random integer between 1 and 59 inclusive (but not 60), please use the following code snippet in your 3 places:
int randomNum = 1 + (int)(Math.random() * 59);
The guess-check logic needs to be fixed (as outlined below):
int noTimes = 0; // Corrected
...
while (guess != randomNum) {
guess = keyboard.nextInt();
noTimes++; // Corrected
}
The last pair of for-loops (the ones just before the 3 consecutive prints) look weird. Here is a more sensible replacement:
System.out.print("The winning numbers are:");
for (int i = 0; i < lottery.length; i++) {
System.out.print(" " + lottery[i]);
}
System.out.println();
System.out.println("You correctly guessed in " + noTimes+ " tries.");
Other than these, your code looks okay to me so far.
PS: Choosing 6 ordered items from 59 elements has 32.4 billion possibilities.

even and odd averages using array

Write a program that reads a list of 10 values from the user. Put the values in an array. The program should read the array and then calculate and display the average of the even input values and the average of the odd input values. This should be done using objects, methods, and a tester class.
I cannot figure out why I am receiving the error:
bad operand types for binary operator.
I do not know what to change. I know something is wrong with my mod (%).
Here is what I have so far for my Average class:
public class Average
{
private int[] numbers = new int[10];
double aveEven, aveOdd,sumEven=0,sumOdd=0;
int oddCounter=0, evenCounter=0;
public Average(int[] n)
{
numbers = n;
if (numbers % 2 == 0)/something is wrong here/
{
evenCounter++;
sumEven+=n;
}
else
{
oddCounter++;
sumOdd+=n;
}
}
public void aveEven()
{
for (int i = 0; i < numbers.length; i++)
{
aveEven = sumEven/evenCounter;
System.out.println("The even average is: " + aveEven);
}
}
public void aveOdd()
{
for(int i = l; i < numbers.length; i++)
{
aveOdd = sumOdd/oddCounter;
System.out.println("The odd average is: " + aveOdd);
}
}
}
For the AverageTester class I have the following:
import java.util.Scanner;
public class AverageTester
{public static void main(String[] args)
{
int[] integer = new int[10];
Scanner input = new Scanner(System.in);
for(int i=0 ; i < 10 ; i++)
{
System.out.print("Please enter a number : ");
integer[i] = input.nextInt();
}
Average example = new Average(integer);
example.aveOdd();
}
}
Also, If you see anything else that could be wrong, please let me know.
Thank you.
numbers is an array, so numbers % 2 is invalid. You should loop over the array and use the % operator on the elements of the array. The += operator should also be applied on a element of the array (i.e. numbers[i]) and not the entire array.
numbers = n;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evenCounter++;
sumEven+=numbers[i];
} else {
oddCounter++;
sumOdd+=numbers[i];
}
}
As for aveEven and aveOdd, since you already compute the sums in the constructor (or at least it seems like that's what you intended to do), you don't need a loop in these methods.
EDIT :
I originally assumed you intended to calculate the average of the numbers in even positions in the array and the average of the numbers in odd positions. After reading the question again, I think the odd/even refers to the numbers themselves, so I changed the code accordingly.
Numbers is an array and comparing an array to an int doesn't work, you could do something like this (depending on your logic):
for(int number : numbers){
if(number % 2 == 0){
evenCounter++;
sumEven += n;
}else{
oddCounter++;
sumOdd += n;
}
}
Few Mistakes
1.) if (numbers % 2 == 0), numbers is an array, use index here and loop. like this if (numbers[i] % 2 == 0).
2.) sumEven += n;, again n is an array here, need to use index.
3.) for (int i = l ; i < numbers.length ; i++) {, you have used l instead of 1.

Categories

Resources