I have to create a lottery game where you randomly generate six winning numbers simulating a lottery. Ask the user to enter six numbers and see if they win the lottery!
I have done a lot of it, but now im stuck. I am really new to java so forgive me. When it prompts to ask for another number it does it but it still displays it for the self-made lottery picks that display. Also, when displaying the numbers for the computer made lottery picks they are the same numbers over again that repeat and aren't 6 numbers. The counter doesn't work as well it maybe a little thing but i can't figure it out. Thank you
package arraysIntroduction;
import java.util.Scanner;
public class sizeQuestion {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int [] user =new int [6];
int i;
//Fill user array
System.err.println("Welcome to Miwand's Lottery");
System.out.println("Please enter your 6 desiered number to enter the lottery");
System.out.println("Pick from 1 to 49");
for ( i=0;i<user.length;i++) // gets numbers until it equals 6
{
System.out.println("Number:");
user[i]= in.nextInt(); // Gets numbers from user
while (user[i] < 0 ) // if its a negative number tell user to enter again
{
System.err.println("Negative number, please enter again:");
user[i]=in.nextInt();
}
if (user[i] > 49) // if the number goes past 49 prompt again
{
System.err.println("Please enter numbers from 1 - 49");
}
}
//print out the numbers generated
for ( i=0;i < user.length; i++){
System.out.print(+user[i]+ " ");
}
System.out.println(" ");
int[] lottery = new int[6];
int guesses;
int counter=0;
int j;
int x;
{
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() *49 +1); // Random number created here.
for ( x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() *49 +1);// If random number is same, another number generated.
}
lottery[j] = randomNum;
}
}
//prints out computer generated numbers
for (i = 0; i < lottery.length; i++){
for (x = 0; x< j; x++){
System.out.print(lottery[i] + " ");
if (user[i] == lottery[x] ){
counter++;
}
}
}
}
if (counter < 2){
System.out.println("Try again!");
}
if (counter == 3){
System.out.println("3 numbers matched! You won $300!");
}
if (counter == 4){
System.out.println("4 numbers matched! You won 500!");
}
if (counter == 5){
System.out.println(" 5 numbers matched! You won $1000!");
}
else if (counter == 6){
System.out.println("JACCKKKPOOOOTTTTTTT!!!!!! YOU WIN 1 MILLION DOLLARS!");
}
}
}
I saw multiple problems in your program.
First, the printout problem can be solved by moving the print statement from inner loop to outer loop
for (i = 0; i < lottery.length; i++) {
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) {
if (user[i] == lottery[x]) {
counter++;
}
}
}
Also, you are not assigning the first random number correctly and it is always using the default, which is 0
Solution:
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() * 49 + 1); // Random number created here.
for (x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 49 + 1);// If random number is same, another number generated.
}
}
lottery[j] = randomNum;
}
Plus, you didn't check if counter is equal to 2
Solution:
if (counter <= 2) {
System.out.println("Try again!");
}
And, the logic in "If random number is same, another number generated." may not be correct, since it may generate the same number again. You need a while loop to generate a new number until it is not equal to any of the generated numbers.
Another thing about coding style is that for any "for loops"
This :
int i=0;
for (i = 0; i < length; i++)
Should be replaced by this:
for (int i = 0; i < length; i++)
As I already said in the comments, you should move the print statement from the inner loop to the outer loop.
Your code should look like this:
for (i = 0; i < lottery.length; i++) { // outer loop
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) { // inner loop
if (user[i] == lottery[x]) {
counter++;
}
}
}
Related
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);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = 0;
do {
System.out.println("How long should we search for primes? Until N=: ");
N = scan.nextInt();
} while (N <= 2); // gets the amount of prime numbers there are that go up to that number
//example, if user enters 20, the output will be that there are 8 prime numbers
boolean[] prime = new boolean[N +2];
for (int i = 2; i <= N; i++) {
prime[i] = true; //makes all values in the array true
}
for (int i = 2; i * i <= N; i++) {
if (prime[i]) {
for (int z = i; z * i <= N; z++) {
prime[i * z] = false; // makes the non prime numbers in the array false
int newCheck = 0;
do {
System.out.println("Enter a number to see if it is prime");
int go = 0;
newCheck = scan.nextInt(); //here's where i need help
} while (newCheck <= 1 || newCheck > N);
if(prime[newCheck]){ // if the number entered is true in the array, it is prime
System.out.println("It is prime");
int mPrime=(int)((Math.log(newCheck))/(Math.log(2)))-1;
if (prime[mPrime]){//ignore this, its for another part i need to do
System.out.println(""+newCheck+ "is a merseinne prime number! It equals 2^"+mPrime+ " -1");
}
}
else if (prime[newCheck]==prime[i*z]){ //if the number is equal to false in the array,
//it is not prime
System.out.println("It is not prime");
}
if(newCheck==0){
break;
}
}
}
}
int counterPrime = 0;
for (int i = 2; i <= N; i++) {
if (prime[i]) {
counterPrime++;
}
}
System.out.println("The number of primes less than or equal to " + N + " is " + counterPrime);
}
I need help with trying to output to the user that the number they entered is prime. So far this example only works for some numbers. The program thinks 14 is prime, 12 is prime, 25 is prime, 35 is prime,36 is prime,39 is prime,and that 34 is prime.
It gets some numbers right though. It knows 8, 10, 12,18 and some other numbers are not prime.
Here is a little method to help you along:
public static boolean isPrime(final int number) {
int temp;
boolean isPrim = true;
for(int i=2; i <= number / 2; i++) {
temp = number%i;
if(temp==0) { isPrim = false; break; }
}
return isPrim;
}
Hope this helps.
I have a problem with a program I am trying to write. A user inputs a positive odd integer, otherwise the program prompts the user until they do. When they do, the program prints a diamond shape corresponding to the user input.
I have this piece so far that prints the left hand diagonal of such a figure, but cannot figure out how to print the rest of it. Here is the code:
import java.util.Scanner;
public class DrawingProgram {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
userInput = keyboard.nextInt();
if (userInput%2 == 0){
System.out.println("That is not a Positive Odd Integer!");
}
else if (userInput < 0){
System.out.println("That is not a Positive Odd Integer");
}
else if (userInput%2 == 1){
for (int row = 1; row<= userInput; row++){
for (int col = 1; col<= userInput; col++ ){
if (row+col==userInput-1 )
System.out.print( "*");
else
System.out.print( " ");
}
System.out.print("\n");
}
}
}
}
A user inputs a positive odd integer, otherwise the program prompts
the user until they do
You need to scan in a loop
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
System.out.println("That is not an Odd Integer!");
if(userInput < 0)
System.out.println("That is not a Positive Odd Integer");
} while(userInput < 0 || userInput %2 == 0);
Now you can remove that validation else if (userInput%2 == 1){
Now the first thing I realize when checking at your loop is if (row+col==userInput-1 || ) which won't compile as you have a comparison operator with nothing following.
Note that you can replace System.out.print("\n"); with System.out.println("") but that's not really important...
Now replace your loop condition so that they start as 0
for (int row = 0; row <= userInput; row++){
for (int col = 0; col <= userInput; col++ ){
Now since you want a Diamond, you need to have 4 diagonal, so 2 loops (one for top and bottom)...
for (int i = 1; i < userInput; i += 2)//Draw the top of the diamond
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//Output correct number of spaces before
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)//Output correct number of asterix
{
System.out.print("*");
}
System.out.print("\n");//Skip to next line
}
for (int i = userInput; i > 0; i -= 2)//Draw the bottom of the diamond
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
So the final code would look like this
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
{
System.out.println("That is not an Odd Integer!");
}
if (userInput < 0)
{
System.out.println("That is not a Positive Odd Integer");
}
} while (userInput < 0 || userInput % 2 == 0);
for (int i = 1; i < userInput; i += 2) //This is the number of iterations needed to print the top of diamond (from 1 to userInput by step of two for example with 5 = {1, 3, 5} so 3 rows.
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//write correct number of spaces before, example with 5 = j < 5 - 1 -i / 2, so it would first print 4 spaces before, with 1 less untill it reach 0
{
System.out.print(" ");//write a space
}
for (int j = 0; j < i; j++)
{
System.out.print("*");//write an asterix
}
System.out.println("");
}
// Same logic apply here but backward as it is bottom of diamond
for (int i = userInput; i > 0; i -= 2)
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
I am trying to finish my assignment but I can't seem to find the bug in my code. It is not a compiler error, and I have been looking at it for hours.
This code is for a game called Mastermind. These are the guidelines (a bit long, I know, but all necessary info for the assignment):
Computer chooses a random 4 digit number, and no digit may repeat itself. (ex: 0462, 2930, 6103 are valid numbers)
The user's goal is to try and guess the computer's chosen number
Once the user makes a guess, the computer will tell the user how class that guess was by giving the following information:
The number of digits matched perfectly (are in the right place)
The number of digits that are off place
When you scan the input from the user, use a String to store it. Your
program must have 4 methods in addition to the main method:
One method named isValidNumber that checks if a given String corresponds to a valid 4 digit number.
One method named perfectMatches that returns the number of perfect matches between two Strings that represent valid 4 digit numbers.
One method named offPlaceMatches that returns the number of ‘off place’ matches between two Strings that represent valid 4 digit
numbers.
One method named generateRandomValidNumber that returns a String that represents a random valid 4 digit number.
Hint: Generate a random 4 digit number by generating a random single
digit 4 times and concatenating them. Then using your isValidNumber
method, check if this String you created is valid. If it is not,
repeat the first part and pick 4 new random digits.
This is my code:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//print welcome, what 4 digit number do you guess...
System.out.println("Welcome to Mastermind.");
System.out.println("I have a 4 digit number in mind. Can you guess it?");
System.out.println("");
System.out.println("What is your guess?");
//string guess is number that is scanned
String guess = input.nextLine();
String validNumber = generateValidNumber();
System.out.print("Perfect matches: " + perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
while(!(perfectMatches(guess, validNumber) == 4)) {
System.out.println("");
System.out.println("What is your guess?");
guess = input.nextLine();
validNumber = generateValidNumber();
System.out.print("Perfect matches: " + perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
}
System.out.println("Yes! You guessed my number correctly. Well done.");
}
static boolean isValidNumber(String number) {
if(number.length() != 4) {
return false; }
char[] numberArray = new char[4];
for (int i = 0; i < 4; i++) {
numberArray[i] = number.charAt(i);
if(!((number.charAt(i) <= '9') && (number.charAt(i) >= '0'))) {
return false;
}
}
for (int i = 0; i < 4; i++) {
char c = numberArray[i];
int count = 0;
for(int j = 0; j < 4; j++)
if(numberArray[j] == c)
count++;
if(count > 1) {
return false;
}
}
return true;
}
static int perfectMatches(String one, String two) {
int counter = 0;
for(int i = 0; i < one.length(); i++) {
if(one.charAt(i) == two.charAt(i)) {
counter++;
}
}
return counter;
}
static int offPlaceMatches(String one, String two) {
int counter = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(i == 0)
continue;
if(one.charAt(j) == two.charAt(i)) {
counter++;
}
if(j == i -1) {
i++;
}
}
}
return counter;
}
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = "";
while(!validNumber) {
for(int i = 0; i < 4; i++) {
char c = (char) (int) (Math.random() * (9));
newNumber = newNumber + c;
}
if(isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
}
There's a problem in the generateValidNumber method.
You are not re-initializing newNumber when you try to find a new random number.
Changing it to the following function should result in the successful execution of the program. Also, multiply the random number with 10 to get an number in the range [0.0, 10.0) (0 included and 10 excluded)
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = null;
while(!validNumber) {
// add this line
newNumber = "";
for(int i = 0; i < 4; i++) {
char c = (char) ('0' + (Math.random() * 10));
newNumber = newNumber + c;
}
if(isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
But there are a few logical errors in the code. For e.g., you are generating a new number everytime a user guesses an invalid number.
Update:
I made a few changes to your code. This should help you get going.
import java.util.Scanner;
public class MastremindString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// print welcome, what 4 digit number do you guess...
System.out.println("Welcome to Mastermind.");
System.out
.println("I have a 4 digit number in mind. Can you guess it?");
System.out.println("");
System.out.println("What is your guess?");
// string guess is number that is scanned
String guess = input.nextLine();
String validNumber = generateValidNumber();
System.out.print("Perfect matches: "
+ perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
while (!(perfectMatches(guess, validNumber) == 4)) {
System.out.println("");
System.out.println("What is your guess?");
guess = input.nextLine();
System.out.print("Perfect matches: "
+ perfectMatches(guess, validNumber));
System.out.println("off place: "
+ offPlaceMatches(guess, validNumber));
}
System.out.println("Yes! You guessed my number correctly. Well done.");
}
static boolean isValidNumber(String number) {
if (number.length() != 4) {
return false;
}
char[] numberArray = new char[4];
for (int i = 0; i < 4; i++) {
numberArray[i] = number.charAt(i);
if (!((number.charAt(i) <= '9') && (number.charAt(i) >= '0'))) {
return false;
}
}
for (int i = 0; i < 4; i++) {
char c = numberArray[i];
int count = 0;
for (int j = 0; j < 4; j++)
if (numberArray[j] == c)
count++;
if (count > 1) {
return false;
}
}
return true;
}
static int perfectMatches(String one, String two) {
int counter = 0;
for (int i = 0; i < one.length(); i++) {
if (one.charAt(i) == two.charAt(i)) {
counter++;
}
}
return counter;
}
static int offPlaceMatches(String one, String two) {
int counter = 0;
for (int i = 0; i < one.length(); i++) {
for (int j = 0; j < two.length(); j++) {
if (one.charAt(j) == two.charAt(i) && i != j) {
counter++;
}
}
}
return counter;
}
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = "";
while (!validNumber) {
newNumber = "";
for (int i = 0; i < 4; i++) {
char c = (char) ('0' + (Math.random() * 10));
newNumber = newNumber + c;
}
if (isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
}
It appears that you are generating a new number on every cycle. The best way to fix this is to not assign to the validNumber variable within main(...) on every loop.
Since you get to the point of "What is your guess?" and you enter a number, but then nothing happens (which presumably means you do not get past the two lines following the first guess=input.nextLine(); call), the function to check first is the generateValidNumber(); function. Second, check your perfectMatches(...); function. You can add System.out.println("blah"); calls to see how far your code gets (as a very crude debugging tool).
I'm assuming you're using Eclipse and in an introductory programming course. An important subject often overlooked in programming courses is how to use a debugger to help you troubleshoot problems. If any of your classmates, lab assistants, or fellow students further along in your major can take 15-30 minutes to sit down and show you how to use the debugger, it will help you through the rest of your programming career.
If not, there are a lot of tutorials you can follow to get familiar with Eclipse's debugger.
To start off, double-click along the left of your code, usually just left of the line numbers. This will add a break point, which will pause your program when it reaches. Add a break point at each of your methods besides main and make sure that all the methods you think should be called are actually called.
When your program is at a break point, you can also take a look at the value of variables in the "Variables" view. If one of them has an unexpected value, you may have found your culprit.
There is a resume button you'll have to hit to resume program execution when you're done at a given break point. It should be next to the Pause and Stop buttons in the top bar by default, and is easy to confuse with the Run button.
First: You never call isValidNumber to check if the user's input is valid. You should call this method and if the number is invalid, the program should terminate or prompt the user for a new number
I'm working to printout ascii art which takes two integers entered from the console then displays a rectangle or square from those two integers (the then dimensions). But the corners need to be a different symbol then the main symbol... yet the trick is that the short side has to have only 1 or 2 of the original symbols on it (due to odd or even.)
Here are two examples:
6x9:
001111100
011111110
111111111
111111111
011111110
001111100
9x6:
001100
011110
111111
111111
111111
111111
111111
011110
001100
I've gotten this far (since the console only goes from 0 to 9 right?)
What would need to be added to take in account the corners?
Would an If statement work or something else?
And yes, I know this is only for the "square". How would I add a second dimension? Can I get some help?
class Main {
public static void printSquare(int size) {
if(size > 9) {
size = 9;
}
int line = 1;
while (line <= size) {
int width = size;
int i = 1;
while (i <= width) {
System.out.print("*");
i = i + 1;
}
System.out.println(); // Newline
line = line + 1;
}
}
}
You need to simply tell it that the three corner symbols are different.
Scanner keys = new Scanner(System.in);
int x = 0;
int y = 0;
public void getInput() {
x = keys.nextInt();
y = keys.nextInt();
createart();
}
public void createart() {
System.out.print("00");
int counter = 0;
while (counter < x - 4) {
System.out.print(1);
counter++;
}
System.out.println("00");
counter = 0;
System.out.print("0");
while (counter < x - 2) {
System.out.print(1);
counter++;
}
System.out.print("0");
counter = 0;
int counter2 = 0;
while (counter < y - 4) {
System.out.println("");
while (counter2 < x) {
System.out.print(1);
counter2++;
}
counter++;
}
System.out.println("");
counter = 0;
while (counter < x - 2) {
System.out.print(1);
counter++;
}
counter = 0;
System.out.println("0");
System.out.print("00");
while (counter < x - 4) {
System.out.print(1);
counter++;
}
System.out.print("00");
}
Simple logic.