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 ?:
Related
I'm trying to store the sum of 2 numbers inside a while loop so that once the loop ends multiple sums can be added up and given as a total sum, however I am rather new to Java and am not sure how to go about doing this.
I'm trying to use an array but I'm not sure if it is the correct thing to use. Any help would be greatly appreciated.
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}
There is a data container called ArrayList<>. It is dynamic and you can add as many sums as you need.
Your example could be implemented like this:
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++)
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}
From what I see, you come from a background of C# (Since I see capital letter naming on all variables). Try to follow the java standards with naming and all, it will help you integrate into the community and make your code more comprehensible for Java devs.
There are several ways to implement what you want, I tried to explain the easiest.
To learn more about ArrayList check this small tutorial.
Good luck!
Solution with array:
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[count]=AddedNum;
count++;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}
This solution is not dynamic. There is risk that length of array defined on beginning will not be enough large.
i'm learning Java with the book think Java : how to think like a computer scientist ? and there is no exercise answers in the book, usually i end up finding similar exercices on different websites but not for this one because i have precise instructions. Can you please tell me if it's correct.
I think the problem is solved, the job is done, but is there an easier way to do it ?
Thanks a lot
Exercise 5-7.
Now that we have conditional statements, we can get back to the “Guess My Number” game from Exercise 3-4.
You should already have a program that chooses a random number, prompts the user to guess it, and displays the difference between the guess and the chosen number.
Adding a small amount of code at a time, and testing as you go, modify the program so it tells the user whether the guess is too high or too low, and then prompts the user for another guess.
The program should continue until the user gets it right. Hint: Use two methods,
and make one of them recursive.
import java.util.Random;
import java.util.Scanner;
public class GuessStarter {
public static void Lower(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too Low , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void Higher(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too high , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100) + 1;
int number2;
System.out.print("Type a number: ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2);}
}
Don't know if it'll be useful now or not, but, as I was solving the same solution, thought of letting it know if someone finds it useful:
import java.util.Random;
import java.util.Scanner;
/**
* Created by RajU on 27-Jun-17.
*/
public class GuessNumber2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
message("I'm thinking of a number between 1 and 10 (including both).\n" +
"Can you guess what it is?\n" +
"Type a number: ");
int userNumber = input.nextInt();
tryAgain(userNumber, calculateRandom(10));
}
public static int calculateRandom(int n) {
Random random = new Random();
return random.nextInt(n) + 1;
}
public static void tryAgain(int userNumber, int generateRandom) {
if (userNumber == generateRandom) {
message("You're absolutely right!");
} else {
if (userNumber > generateRandom) {
message("Think of a lesser number: ");
} else {
message("Think of a greater number: ");
}
userNumber = input.nextInt();
tryAgain(userNumber, generateRandom);
}
}
public static void message(String m) {
System.out.print(m);
}
}
I just completed this exercise. It's pretty interesting to see some different approaches! Here's my take on it:
import java.util.Random;
import java.util.Scanner;
public class GuessGameLevelUp {
/*
* A guessing game where you try to guess a random number between and including 1 and 100.
* This version allows you to continue guessing until you get the right answer.
* When you're off, a hint will let yet know whether your most recent guess was too high or low.
*/
public static void main (String [] args) {
//Generates a random number for the game
Random random = new Random();
int answer = random.nextInt(100) +1;
//Introduces the game and gives a prompt
System.out.println("I'm thinking of a number between and including "
+ "1 and 100, can you guess which?");
System.out.print("Take a guess: ");
//Enables guess value input and parrots guess
Scanner in = new Scanner(System.in);
int guess;
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
//Stacks a new class to determine the outcome of the game
tooHighTooLow(answer, guess);
}
public static void tooHighTooLow(int a, int g) {
//Triggers and parrots guess if correct
if (a==g) {
System.out.print("Correct! The number I was thinking of was: "+g);
//Triggers "Too Low" prompt and uses recursive to offer another attempt
} else if (a>g) {
System.out.print("Too Low! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
//Triggers "Too High" prompt and uses recursive to offer another attempt
}else
System.out.print("Too high! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
}
}
I got stuck on this one too, but your code helped me in arriving at a solution. Here's what I came up with:
import java.util.Random;
import java.util.Scanner;
public class Ch5Ex7 {
public static void compareNumbers(int userNumber,int randomNumber) {
if(userNumber == randomNumber) {
System.out.println("You got it!");
} else if ( userNumber > randomNumber ) {
System.out.println("Too high. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
} else {
System.out.print("Too low. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber,randomNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
int userNumber;
System.out.print("Type a number: ");
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
}
}
Thanks for pointing me in the right direction!
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 ;)
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
i am mking a program where the computer guesses your number. and it has to guess a random num. but how do i make the random line be lower or higher num than the perviously num guessed?
package compguse;
import java.util.*;
public class Compguse {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String a;
String b;
String c;
String ans;
String d;
int input =1;
System.out.println("do u have your number?");
a = scan.nextLine();
while (a.equalsIgnoreCase("yes"))
{
int ran = (int) Math.floor(Math.random()*100)+1;
System.out.println(" is" +ran +" your num?");
a = scan.nextLine();
if(a.equalsIgnoreCase("no"))
{
System.out.println("Was i too high or low?");
b = scan.nextLine();
if(b.equalsIgnoreCase("high"))
{
int ran1 = (int) Math.floor(Math.random() < (int) ran);
}
}
}
}
Just make a while loop which implements this pseudocode:
For example if you want it to be less than the guess:
while random is greater than guess
random = new random number
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.