Lottery - guess correct number - java

Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.print("Enter a number u wish(1-1000): ");
int unos = input.nextInt();
int rand = random.nextInt(1000) + 1;
System.out.println(rand);
if (unos = random) {
System.out.printf("Congratz u won");
}
while (unos < rand) {
System.out.println("Your number is lower \t Try again: ");
unos = input.nextInt();
}
while (unos > rand) {
System.out.println("Your number is higher\t Try again: ");
unos = input.nextInt();
}
So, if I hit numbers that aren't equal to the randomly generated number it works, but once I hit, it doesn't output "Congratz u won". It just terminates. Why?
import java.util.Scanner;
import java.util.Random;
public class Lutrija {
public static void main(String []args){
Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.print("Uneti broj koji mislite da ce ispasti(1-1000): ");
int unos=input.nextInt();
int rand =random.nextInt(1000)+1;
System.out.println(rand);
while (unos!=rand){
if(unos==rand){
System.out.println("Congratz");
}
else if (unos>rand){
System.out.println("broj je veci od izvucenog");
unos=input.nextInt();
}
else if (unos<rand){
System.out.println("broj je manji od izvucenog");
unos=input.nextInt();
}
}
}
}
This doesn't work, why?

You are using assignment = instead of equality test == in your if statement. Change to:
while ((unos = input.nextInt()) != rand) {
// Tell them higher of lower
// No need to call input.nextInt() in loop body as it is called
// when reevaluating while condition
}
// Congratulate them since to get here, unos == rand
You also should embody your code in a single loop that loops until guess equals the random number otherwise it just terminates as none of the while conditions will hold.

Related

Multiplication proctoring program

I am working on a project for school and am at a loss for ideas after searching online and looking at loop flow charts, and different methods to accomplish what is required.
The requirements are:
Generate two, 1 digit integers, and ask the user to find the product of said two.
If wrong, print "No. please try again. " & prompt the user for input to try again forever until correct.
If correct, print "Very good! " & prompt question with two new integers.
I am confused as to what kind of loops to use, and how to order them in order to serve their purpose.
import java.util.Scanner; // Program utlizes scanner
import java.security.SecureRandom; // Program utlizes SecureRandom
public class WaringComputerAided {
static void callNumbers() { //method to generate random numbers
SecureRandom rand = new SecureRandom();
Scanner input = new Scanner(System.in);
int num1 = rand.nextInt(10); //generates random integer #1
int num2 = rand.nextInt(10); //generates random integer #2
System.out.printf("How much is "+num1+" times "+num2+" ?: "); // Asks question
int sum = (num1 * num2);
}
static void tryAgain() {
Scanner input = new Scanner(System.in);
System.out.printf("No. Please try again. ");
int answer = input.nextInt();
}
public static void main(String[] args) {
SecureRandom rand = new SecureRandom();
Scanner input = new Scanner(System.in);
int num1 = rand.nextInt(10);
int num2 = rand.nextInt(10);
int sum = (num1 * num2);
do { // Asks question first time, and asks new question when user inputs correct answer
callNumbers(); //Generates numbers and asks new question
int answer = input.nextInt(); // Asks user for input
} while(answer == sum);
if (answer != sum) { // When answer incorrect
tryAgain();
}
if (answer == sum) { // When answer is correct
System.out.printf("Very good! ");
}
} // End method main
} // End class product
First of all your callNumbers method is not returning anything change it to int and return the sum
static int callNumbers() { //method to generate random numbers
SecureRandom rand = new SecureRandom();
// Scanner input = new Scanner(System.in);
int num1 = rand.nextInt(10); //generates random integer #1
int num2 = rand.nextInt(10); //generates random integer #2
System.out.printf("How much is "+num1+" times "+num2+" ?: "); // Asks question
int sum = (num1 * num2);
return sum;
}
At the tryAgain method we need to change the logic if it is incorrect then just call main method to repeat the procedure
static void tryAgain() {
System.out.printf("No. Please try again. ");
main(new String[]{});
}
We want to get the correct answer so we save it to a new variable so then we can compare it with the number user has entered
sum = callNumbers();
The do while logic
do {
sum = callNumbers();
answer = input.nextInt();
if (answer != sum) { // When answer incorrect
tryAgain();
}
if (answer == sum) { // When answer is correct
System.out.printf("Very good! ");
}
} while(answer == sum);
All the code
import java.util.Scanner; // Program utlizes scanner
import java.security.SecureRandom; // Program utlizes SecureRandom
public class WaringComputerAided {
static int callNumbers() { //method to generate random numbers
SecureRandom rand = new SecureRandom();
// Scanner input = new Scanner(System.in);
int num1 = rand.nextInt(10); //generates random integer #1
int num2 = rand.nextInt(10); //generates random integer #2
System.out.printf("How much is "+num1+" times "+num2+" ?: "); // Asks question
int sum = (num1 * num2);
return sum;
}
static void tryAgain() {
System.out.printf("No. Please try again. ");
main(new String[]{});
}
public static void main(String[] args) {
SecureRandom rand = new SecureRandom();
Scanner input = new Scanner(System.in);
int num1 = rand.nextInt(10);
int num2 = rand.nextInt(10);
int sum = 0;
int answer = 0;
do {
sum = callNumbers();
answer = input.nextInt();
if (answer != sum) { // When answer incorrect
tryAgain();
}
if (answer == sum) { // When answer is correct
System.out.printf("Very good! ");
}
} while(answer == sum);
}
}
OUTPUT
How much is 9 times 1 ?: 23
No. Please try again. How much is 6 times 0 ?: 6
No. Please try again. How much is 4 times 3 ?: 2
No. Please try again. How much is 7 times 1 ?: 7
Very good! How much is 0 times 0 ?: 0
Very good! How much is 4 times 4 ?:

I need to type number 2 times after my scanner scan the input

Could you help me to understand why I need to type 2 times to allow scanner to scan my input data.
What I am basically check in below piece of code is to validate if number is a int type and is above 0 to ask number of players playing the game (guessing number game)
Validation code works perfectly fine but...I need to type digit 2 times...
package pakiet;
import java.util.Random;
import java.util.Scanner;
public class GraModyfikacjaLiczbyGraczy {
public static void main(String[] args) {
Random rand = new Random();
int los = rand.nextInt(11);
int liczbaGraczy; // number of players
Scanner scan7 = new Scanner(System.in); // zamknac
System.out.println("Type number of players");
while (!scan7.hasNextInt() || scan7.nextInt() < 0) {
System.out.println("Type number of players");
scan7 = new Scanner(System.in);
}
liczbaGraczy = scan7.nextInt();
You initialize Scanner 2 times thats why -
In while loop -
while (!scan7.hasNextInt() || scan7.nextInt() < 0) {
System.out.println("Type number of players");
//Issue here
scan7 = new Scanner(System.in);
}
You can simply use scan7.next() for next input.
You can use do-While loop properly to achieve this -
public static void main(String[] args) {
Random rand = new Random();
int los = rand.nextInt(11);
int liczbaGraczy; // number of players
Scanner scan7 = new Scanner(System.in); // zamknac
System.out.println("Type number of players");
do {
while (!scan7.hasNextInt()){
System.out.println(" Type number of players :");
scan7.next();
}
liczbaGraczy = scan7.nextInt();
}while (liczbaGraczy < 0);
System.out.println("Number of players :"+liczbaGraczy);
}
Hope this will help.

Java array and nextInt(); do not work properly

Hello guys I am having a problem with an array and a .nextInt(); this is causing my output line at the 3rd prompt to shift up instead of under, and seriously cannot figure out what's wrong.
I have tried .hasNextInt(); but nothing, it actually gives me an error, so here is the code:
import java.util.Random;
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn); //my problem
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //my problem
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2];
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
// Method for calculations
public static double compute(int numOfSimulation, int numOfPeople)
{
for (int i =0; i < numOfPeople; i++)
{
Random rnd = new Random(1);
//Generates a random number between 0 and 364 exclusive
int num = rnd.nextInt(364);
System.out.println(num);
System.out.println(num / 365 * numOfPeople * numOfSimulation);
}
return numOfPeople;
}
}
Found it!!!!!!!!!!!
do this:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return(userInput);
}
To return the array
Let me know!
I actually don't think you can do it there with that userInput, I am saying this because the methodology of doing this program is quite arcane.
You are then calling 2 arrays at prompting, I wonder if you might change that to one what will change such as:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
As also the return promptAndRead(stdIn); might be part of the problem
Don't know though just trowing suggestions at Markov ;)

How do I output a TABLE with names and scores with only using Arrays and Methods?

I have been trying to find the answer to this question but to no avail!
Basically I have to write a program where 'x' number of players can enter a guessing game and input their guesses and then get a score.
However, right after they input their guesses, i have to output it in a table form like this "NAME GUESS SCORE"
I do not know how i can do this with a for loop since a for loop println can only print values from playersArray. How can I print another array like guessesArray to the side of it?
I can only use Arrays and Methods to do this.
Below I will show u what i have right now:
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class game
{
static int[] guessesArray;
static int guess;
static String [] playersArray;
static int[] currscoresArray;
static int [] addscoresArray;
static int [] finalscoresArray;
public static void main(String [] args){
System.out.print("Number of players? ");
Scanner kb = new Scanner(System.in);
int numplayers = kb.nextInt();
//Initialize
playersArray = new String[numplayers];
guessesArray = new int [numplayers];
currscoresArray = new int [numplayers];
addscoresArray = new int [numplayers];
finalscoresArray = new int [numplayers];
populateArray(playersArray);
displayMenu();
}
public static void populateArray( String[] x){
Scanner kb = new Scanner(System.in);
for (int i = 0; i<x.length ; i++){
System.out.print("Enter Player "+(i+1)+": ");
x[i]=kb.nextLine();
}
}
public static void displayMenu(){
int choice=0;
Scanner kb = new Scanner(System.in);
String[] args = {};
while(true){
System.out.println("Menu ");
System.out.println("1. Make Guess");
System.out.println("2. List Winner");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = kb.nextInt();
if (choice==0){
System.out.print("Do you want to play a new game? Y/N: ");
String ans = kb.next();
if (ans.equals ("Y") || ans.equals ("y")){
main(args);
}
break;
}
switch (choice){
case 1: makeGuess(); break;
case 2: listWinner(); break;
default: System.out.println("Invalid choice");
}
}
System.out.println("End of program");System.exit(0);
}
public static void makeGuess(){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int secret = rand.nextInt(10)+1;
for (int i=0; i < guessesArray.length; i++){
System.out.print("Enter your guess "+playersArray[i]+": ");
guessesArray[i]=kb.nextInt();
}
int diff = (int)(Math.abs(guess - secret));
int score=0;
if (diff == 0){
score=score+10;
}else if(diff<=1){
score=score+5;
}else if(diff<=2){
score=score+2;
}
for (int i=0; i< currscoresArray.length; i++){
currscoresArray[i]=score;
}
System.out.println();
System.out.println("Generated number is "+secret);
System.out.println("Current Score Listing");
System.out.println(" Name Guess Score Added Final Score");
System.out.println("1. "+playersArray[0]+" \t "+guessesArray[0]+" \t"+currscoresArray[0]+"");
System.out.println("1. "+playersArray[1]+" \t "+guessesArray[1]+" \t"+currscoresArray[1]+"");
}
public static void listWinner(){
}
}
just reuse a int x variable when printing from each array?
for( int x = 0; x < playersArray.length; x++ ) {
System.out.println( playersArray[ x ] + ” ” + guessArray[ x ] + " " + finalScoresArray[ x ] );
}
you already give an example in your code where you print the 3 values with a single print method. you used a for loop for indexing an element in an array. So combing the 2 techniques shouldn't be too difficult to grasp.
Instead of using an enhanced for loop (e.g. for (String player : playersArray) {}, you can use an indexed one:
for (int i = 0; i < playersArray.length; i++) {
String name = playerArray[i];
double score = scoresArray[i];
}
That being said, you should really make a Player class, that holds all information of a single player, and then have just one array, of that type. That's much nicer, not only because you can use enhanced fors, but because you don't need to make sure the arrays are always synced, and your code becomes way easier to understand.

How can the numbers in array count to odd or even number?

I wrote the code in java but it does not count to odd or even. It only counts in even numbers. If I miss anything?
import java.util.Scanner;
public class OddEven {
//create the check() method here
static void check(int[] x, int n) {
x = new int[100];
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
x[n++] = in.nextInt();
}
if (x[n] % 2 == 0) {
System.out.println("You input " + n + " Even value");
} else if (x[n] % 2 == 1) {
System.out.println("You input " + n + " Odd value");
}
while (in.hasNextInt()) ;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//read the data here
System.out.print("Input a list of Integer number : ");
int[] x = new int[100];
int n = 0;
check(x, n);
in.close();
}
}
Check these loops:
This essentially puts all the ints in x.
while(in.hasNextInt()) {
x[n++] = in.nextInt();
}
This just loops until it doesn't have an it.
while(in.hasNextInt());
Which means, the if block is not even in a loop. However, the first while loop post increments n, which means even if you have one number, it will assign:
x[0] = 123;
but then n=1. which means, the if block will check the next field. But by default it is 0, which will display that it is even.
This would make more sense:
x= new int[100];
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
x[n] = in.nextInt();
if(x[n]%2==0){
System.out.println("You input "+n+" Even value");
}else if(x[n]%2==1){
System.out.println("You input "+n+" Odd value");
}
n++;
}

Categories