Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to create a lottery program that creates four random numbers, each between 0 and 9 (inclusive). This program asks user to guess four numbers and compares each user guesses to four random numbers and displays the won message as:
No matches 0 points
Any one digit matching 5 points
Any two digits matching 100 points
Any three digits matching 2,000 points
All four digits matching 1,000,000 points
My program runs but it has some logic errors. For example,the output should be:
Random numbers:2 3 3 4
Guess numbers: 1 2 5 7-->1 matching digit
Guess numbers: 3 5 7 3-->2 matching digits
Guess numbers: 3 3 3 1-->2 matching digits
Guess numbers: 3 3 3 3-->2 matching digits
public class Lottery
{
public static void main(String[] args) {
final int LIMIT=10;
int totalCount=0;
int totalPoint;
Random random=new Random(); //creating object of random class
Scanner input=new Scanner(System.in);//creating object of scanner class
//declaring two arrays
int[] guessNumber= new int[4];
int[] randomNumber=new int[4];
for(int i=0;i<4;i++)
{
randomNumber[i]=random.nextInt(LIMIT);//returns value between 0 to 9(inclusive)
}
for(int i=0;i<4;i++)
{
System.out.println("Enter your first guess number from 0 to 9:");
guessNumber[i]=input.nextInt();
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (randomNumber[i] == guessNumber[j])
{
++totalCount;
break;
}
}
}
if(totalCount == 1)
{
totalPoint=5;
}
else if(totalCount == 2)
{
totalPoint=100;
}
else if(totalCount == 3)
{
totalPoint=2000;
}
else if(totalCount == 4)
{
totalPoint=100000;
}
else
{
totalPoint=0;
}
//dispalying points
System.out.println("You have earned " +totalPoint+ "points!!");
}
}
Looks to me like the problem is that once you've matched a particular digit, you ought to be removing it from circulation so that multiple guesses of the same value don't count as matches. One solution is to use an ArrayList for the randomNumber's and remove them when there's a match. If you replace what's between your // declaring two arrays comment and your totalPoint assignment with the following it seems to do what you requested in terms of your example.
int guess;
ArrayList<Integer> randomNumber = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
randomNumber.add(random.nextInt(LIMIT));
}
for (int i = 0; i < 4; i++) {
System.out.print("Enter your guess number from 0 to 9: ");
guess = input.nextInt();
for (int j = 0; j < randomNumber.size(); ++j) {
if (randomNumber.get(j) == guess) {
++totalCount;
randomNumber.remove(j);
break;
}
}
}
input.close();
Note that I've chosen to process each guess as it's read rather than store them in an array and process them later.
It looks like your overall logic is fine.
If I understand correctly, you just want a different output.
Use something like this for your output.
String guessNumbers = "";
String randomNumbers = "";
for (int i = 0; i < 4; i++){
randomNumbers += randomNumber[i]+" ";
guessNumbers += guessNumber[i]+" ";
}
System.out.println("Random numbers: "+randomNumbers);
System.out.println("Guess numbers: "+guessNumbers+" --> # of matching digits "+totalCount);
System.out.println("You have earned " +totalPoint+ " points!!");
This is what it now prints:
Random numbers: 2 9 7 4
Guess numbers: 7 4 5 2 --> # of matching digits 3
You have earned 2000 points!!
Related
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.
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to write a program that reads a sequence of integers and divide it into two sequences. The values on odd positions will be the first sequence and the values of even positions will be the second sequence. The program prints the elements of the first sequence and then the elements of the second sequence separated by a single space. The first input value specifies the number of elements.
Input: 7 1 2 4 5 6 8 9
Expected Output: 1 4 6 9 2 5 8
My Output: 2 0
package twosequences;
import java.util.Scanner;
public class TwoSequences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] values = new int[n];
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
}
int odd = 0;
int even = 0;
int i = 1;
if (i % 2 == 0) {
even = values[i];
} else {
odd = values[i];
}
i++;
System.out.printf("%d %d%n", odd, even);
}
}
I'm not sure why I'm outputting 2 0. Any suggestions?
You need two different loops to iterate over even and odd elements respectively to obtain the desired output.
for (i = 0 ; i < n ; i += 2) {
even = values[i];
System.out.printf("%d ", even);
}
for (i = 1 ; i < n ; i += 2) {
odd = values[i];
System.out.printf("%d ", odd);
}
Hope this helps.
Print the even-numbered elements in one loop; then use another loop to print the odd-numbered elements.
System.out.print(values[0]); // print by itself to avoid prepending " ".
for (int i = 2; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
for (int i = 1; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
System.out.println();
you take the second element of an array (2), and only for that one you are checking if it's even or not.
The result goes true for first 'if', and
even = 2;
, the if statement ends and odd stays as declares (0), that' why u got result like that.
If you want output whith more than 2 integers, you need to change
, where n would be all scanned even numbers.
Try to put a counter in first for loop, like
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
if(values[i]%2==0) evenCounter++;
}
Now to count odds just count values.length - evenCounter.
Also you do not need to make simple arrays like int[], you can go with
List<Integer> list = new ArrayList<>();
You will be able to add elements in for loop withour knowing how many elements you will be implementing.
Hope some of those helps.
I'm kind of a newbie at Java, and not very good at it. It's a trial and error process for me.
I'm working on a Java program to output the amount of primes in an array. I can get it to output the primes, but I want to also output the quantity of primes. I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. It doesn't work as intended. The count is actually off. When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. I think it might be counting 1 as a prime. Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though.
Here's my code
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
Forgive the sloppiness of it. I actually plan on adding multithreading to it, but I wanted to get this down first.
Any help would be greatly appreciated. Thanks.
You have included 1 in your array of primes, because you started the n for loop at 1. You don't print it because of the final if statement, but it's there in the ArrayList.
Start your n for loop with n = 2. As a consequence, you won't need the final if statement, because n won't be 1 ever. You could print the prime at the same time as you add it to the ArrayList.
I have an array filled with 50 numbers and cannot figure how to output the array into a table like format.
Currently when I print my array it is being outputted into one long line of numbers, and what I am aiming for is 10 lines, each consisting of 5 numbers.
Furthermore I would prefer each value to be a 3 digit value. So 1 would be represented as 001, to improve readability and presentation.
import java.util.*;
public class Random50 {
public static void main (String[] args)
{
final int MAX_SIZE = 50;
int[] r50 = new int[MAX_SIZE];
Random rand = new Random();
for (int i=0; i<r50.length; i++)
{
r50[i] = rand.nextInt(1000);
for (int j=0;j<i;j++)
{
if (j!=i && r50[i] == r50[j])
{
System.out.println("Duplicate: " + r50[i]);
r50[i] = rand.nextInt(1000);
}
}
}
System.out.printf(Arrays.toString(r50));
}
}
You really should only ask 1 question per post so I'll answer your first question - it makes it so other users can find relevant information in the future (not trying to be mean).
If you want to start printing on a new line every fifth number you could make use of the modulus operator %.
for(int i = 0; i < 50; i++){
if(i % 5 == 0){ // True every fifth value
System.out.print("\n"); // Print a new line
}
... // Your other code goes here
}