I am in the process of making a program which will display 3 problems of operation type which a user picks. I've used a loop to keep the program generating random numbers for each iteration as well as to display another problem. The problem I'm having is in trying to clear the scanner after taking user input as to not keep the wrong value stored and screw up the loop. I need the one value ("a") to be stored so that the loop continues with the next question. For this post I've taken out all options but addition just for debugging purposes. My code I will paste below:
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
Random randGen = new Random(Config.RANDOM_SEED);
// Welcome
System.out.println("Hello and welcome to the Math Trainer!\n======================================");
System.out.println("Which math operation would you like to practice?");
// Create a counter for correct answers
int correctCount = 0;
// Create a for loop to generate multiple questions
for (int count = 0; count < Config.NUMBER_OF_QUESTIONS; count++) {
// Calculate random values from seed and shift them within range
int ran1 = randGen.nextInt(Config.MAX_VALUE - Config.MIN_VALUE + 1);
int ran2 = randGen.nextInt(Config.MAX_VALUE - Config.MIN_VALUE + 1);
int ran1Shift = ran1 + Config.MIN_VALUE;
int ran2Shift = ran2 + Config.MIN_VALUE;
// Initialize different answers per operation
double additionAnswer = (double) ran1Shift + ran2Shift;
double subtractionAnswer = (double) ran1Shift - ran2Shift;
double multiplicationAnswer = (double) ran1Shift * ran2Shift;
double divisionAnswer = (double) ran1Shift / ran2Shift;
double remainderAnswer = (double) ran1Shift % ran2Shift;
// Ask for user input on which to choose (only on first run of loop)
if (count == 0) {
System.out.println(" " + "[A]ddition");
System.out.println(" " + "[S]ubtraction");
System.out.println(" " + "[M]ultiplication");
System.out.println(" " + "[D]ivision");
System.out.println(" " + "[R]emainder");
System.out.print("Enter your choice:" + " ");
}
// Presentation of addition problems
if (stdin.nextLine().equalsIgnoreCase("a")) {
System.out.print(
"What is the solution to the problem:" + " " + ran1Shift + " " + "+" + " " + ran2Shift + " = ");
if (stdin.hasNextDouble()) {
double userNum = stdin.nextDouble();
stdin.nextLine();
if (userNum == additionAnswer) {
System.out.println("That is correct!");
correctCount++;
} else {
System.out.println("The correct solution is: " + additionAnswer + ".");
}
} else {
stdin.nextLine();
System.out.println("All solutions must be entered as decimal numbers.");
System.out.println("The correct solution is " + additionAnswer + ".");
}
} else {
System.out.println("I'm sorry, I only understand choices of: A, S, M, D, or R!");
count--;
}
}
// Program exit
System.out.println("*** You answered " + correctCount + " out of 3 questions correctly. ");
System.out.println("======================================");
System.out.println("Thank you for using the Math Trainer!");
}
}
The output I get if I enter the correct answer to the first problem (13) is:
https://gyazo.com/773f9be3b51f51f5086f38f36ed0c86b
In which I have to enter "a" again for the next question to show.
The output I should get is here:
https://gyazo.com/6609a9f0b44d0b446439d3331be51eb9
Please let me know if you have any questions and thank you very much for your help.
if (stdin.nextLine().equalsIgnoreCase("a")) this is the cause of your problem.
For a quick fix, move the codes asking for operationType to outside of the loop since it's only executed once.
System.out.println(" " + "[A]ddition");
System.out.println(" " + "[S]ubtraction");
System.out.println(" " + "[M]ultiplication");
System.out.println(" " + "[D]ivision");
System.out.println(" " + "[R]emainder");
System.out.print("Enter your choice:" + " ");
String operationType = stdin.nextLine();
for (int count = 0; count < Config.NUMBER_OF_QUESTIONS; count++) {
//codes
if (operationType.equalsIgnoreCase("a")) {
Might be better to use a switch statement for checking the operationType too.
Related
How to keep the smoke set changing while the rocket goes up?
I don't understood very well, but the set only changes while the rocket is at the base.And he wasn't supposed to stand still.
veja o movimento do vĂdeo no link ->
https://i.imgur.com/RRvFqBR.mp4
The loop for(int h = 0; h < 29; h++){ maintains the set by changing the condition of the increment, and only takes off after that. Then the set stops changing.
#include <unistd.h>
#include <stdio.h>
#define LINE 11
#define COLN 12
#define R_COLN 12
#define R_LINE 9
#define R_SET 2
#define DELAY 95000
//string to display the rocket
const char rocket[LINE][COLN+1]={
" ^ ",
" /^\\ ",
" |-| ",
" |R| ",
" |O| ",
" |C| ",
" |K| ",
" |E| ",
" /|T|\\ ",
" / | | \\ ",
" | | | | "
};
const char smoke[R_SET][R_LINE][R_COLN+1]={
{
" ' * ",
" * + . ' ",
" - . + ",
" . ' : . ",
" + ' ' * . ",
" . * . ",
" . ' : ",
" . ' . ",
" ' "
},
{
" * ' ",
" ' . + * ",
" + . - ",
" . : ' . ",
" . * ' ' + ",
" . * . ",
" : ' . ",
" . ' . ",
" ' "}
};
int main(){
int jumpControlAtBottom = 0;
int shifControl = 0;
int smoke_set = 0;
for(int h = 0; h < 29; h++){ //frame
for (jumpControlAtBottom = 0; jumpControlAtBottom < 28; ++jumpControlAtBottom){
// Jump to bottom of console
printf("\n");
}
for(int i = 0; i< LINE; i++){
printf("%.*s\n", COLN, rocket[i]);
}
for(int y=0; y<R_LINE; ++y){
printf("%.*s\n", R_COLN, smoke[smoke_set][y]);
}
smoke_set=(smoke_set+1)%R_SET; // Advance to the next set
// (or go back to the first one).
fflush(stdout); // Draw the current frame on the screen.
usleep(DELAY); // Pause to be visible.
}
for (shifControl = 0; shifControl < 28; ++shifControl){
// Rocket move on the basis of delay
usleep(DELAY);
// move rocket a line upward
printf("\n");
}
return 0;
}
Currently your logic is:
Draw one frame.
Change smoke set.
Repeat 1-2 for 29 frames.
Draw line to push frame up.
Repeat 4 to keep pushing frames up.
From that it is obvious the smoke will stop changing at step 4. So the logic needs to include the take off elevation in step 1. The easiest way to do that is to put the draw frame into a function and add the elevation as a parameter.
Here is an example:
void draw_frame(int elevation)
{
int jumpControlAtBottom = 0;
static int smoke_set = 0;
for (jumpControlAtBottom = 0; jumpControlAtBottom < 28 + elevation; ++jumpControlAtBottom){
// Jump to bottom of console
printf("\n");
}
for(int i = 0; i< LINE; i++){
printf("%.*s\n", COLN, rocket[i]);
}
for(int y=0; y<R_LINE; ++y){
printf("%.*s\n", R_COLN, smoke[smoke_set][y]);
}
smoke_set=(smoke_set+1)%R_SET; // Advance to the next set
// (or go back to the first one).
// Push image up by elevation
for (int ix = 0; ix < elevation; ix++) {
printf("\n");
}
fflush(stdout); // Draw the current frame on the screen.
usleep(DELAY); // Pause to be visible.
}
int main(){
int shifControl = 0;
// No elevation - engine starting up
for(int h = 0; h < 29; h++){ //frame
draw_frame(0);
}
// take off has occured
for (shifControl = 0; shifControl < 28; ++shifControl){
// Rocket move on the basis of delay
// move rocket a line upward
draw_frame(shifControl);
}
return 0;
}
It seems to me like you're struggling to understand the procedural nature of C, which probably means you're guessing and playing around with code from other (probably poor) examples.
This is akin to guessing how to prepare a chicken for cooking and then asking your guests how to prepare a chicken for cooking, after the chicken is cooked. You have an application that does most of what you want. How did you come up with this code, yet not know how to apply such a simple tweak?
If you don't understand the procedural nature of C, it stands to reason that any exercise that has you read the procedural nature of C in order to extract some logic and repeat it is terrible for you. Where is your book? Start with the basics.
To be clear, this answer may not seem relevant, but it does actually answer your question: you need to hoist some of your smoke-related logic out into a different function so that you can reuse it later... but before you do that, you need to be able to read C, and we're not here to do your work for you, rather to guide you in the right direction.
I am trying to make a game in drjava, in which two players play a two-player game called 'Remove the Last Stone'. I have successfully coded the core of the game. However, after the game finishes, I am required to give the user three options on how they want to proceed after playing the initial starting game. The three options are:
1) Play another game with the same players.
2) Exit the game.
3) Play another game with different players.
So basically, my game would prompt the two players that initially started with playing the game to enter '1' if they want to play another game. What pressing this key would do, is that instead of asking for the players' names again, it would directly ask how many rounds they want to play, and continue on with the rest of the game. At the end of the initial game, the user could enter '2' if 2 other/different players want to play the game. What my code is supposed to do in this case, is to loop back to the very beginning of the code, in which it asks for the names of the players, since two new players are playing. Finally, the user can choose to enter '3' to exit out of the game. I have tried to code this, but for some reason, I am having issues with looping back to 2 different parts of my game code based on the user's input between pressing '1' and '2'. I am also having problems with exiting the game, when the user chooses to press 3. My issue is that when any of these 3 keys are pressed ('1', '2', or '3'), my game repeatedly asks how many rounds the user want to play. This is not supposed to happen, as these 3 keys are supposed to perform different operations.
Here is my game code:
// Import the Scanner class
import java.util.Scanner;
public class StrategyGame {
public static void main(String[] args) {
// Create a new Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Variable declarations
String namePlayerOne, namePlayerTwo;
String lastPlayerTurn = "";
boolean playDifferentGame = true;
boolean playSameGame = true;
boolean playRounds = true;
boolean validInputPlayerOne = false;
boolean validInputPlayerTwo = false;
boolean validProceed = false;
int userGameRounds, playerRemoveLimit, gameStonePile, playerTwoRemoval, proceedChoice;
int playerOneRemoval = 0;
int numRounds = 0;
int playerOneWins = 0;
int playerTwoWins = 0;
// Do while loop responsible for executing whole game first, then repeatedly loops if the same two
// players that started the game want to play again
do {
System.out.println();
System.out.println("Player 1, please enter your name:");
namePlayerOne = keyboard.nextLine();
System.out.println("Player 2, please enter your name:");
namePlayerTwo = keyboard.nextLine();
System.out.println();
// Display game instructions and how to play game
System.out.println(namePlayerOne + " and " + namePlayerTwo + ", welcome to the Strategy Game!"
+ " The rules of this game are very simple. You guys will be iteratively asked"
+ " to remove some stones from a pile of stones, which will total different amounts"
+ " for each round. For each round, you will only be allowed to remove a specific maximum"
+ " number of stones. A round from the game will finish when either one of you removes the"
+ " remaining stones and there are zero stones left in the pile. You will be asked how many"
+ " rounds you want to play, and so, a game will finish when your chosen number of rounds"
+ " have been completed.");
// Do while loop that repeatedly loops, after the very first game, if two different players want to play
do {
System.out.println();
System.out.println("How many rounds would you like to play? You can select between 2-5 rounds inclusively.");
userGameRounds = keyboard.nextInt();
// Ask user how many rounds they want to play, between 2-5 rounds (inclusively)
while (userGameRounds < 2 || userGameRounds > 5) {
System.out.println();
System.out.println("Invalid input. Please try again.");
userGameRounds = keyboard.nextInt();
}
// If user-input is valid; enters into execution of game rounds
while (playRounds == true) {
gameStonePile = (int) (11 * Math.random() + 10);
playerRemoveLimit = (int) (3 * Math.random() + 2);
numRounds = numRounds + 1;
System.out.println();
System.out.println("It is now round " + numRounds + ". For each turn, each player"
+ " is only allowed to remove a maximum of " + playerRemoveLimit + " stones.");
System.out.println("** Important Note: Each player should also avoid removing stones that exceed"
+ " the number of stones that are remianing in the stone pile, even if the amount you"
+ " remove is within the removing limit range. (i.e., You remove 3 stones, when 2 stones are left in pile.)"
+ " **");
// Until game stone pile reaches zero, the 2 players continue alternating turns
while (gameStonePile != 0) {
if (gameStonePile != 0) {
do {
validInputPlayerOne = false;
System.out.println();
// Player One's turn
System.out.println(namePlayerOne + ", it is your turn. Please enter the amount of stones you want to remove."
+ " In the stone pile currently, there are " + gameStonePile + " stone(s).");
// Get amount Player 1 wants to remove from current/remaining stone pile
playerOneRemoval = keyboard.nextInt();
while (playerOneRemoval < 1 || playerOneRemoval > playerRemoveLimit || playerOneRemoval > gameStonePile) {
System.out.println("Invalid input. Please try again.");
playerOneRemoval = keyboard.nextInt();
}
// Subtract amount Player 1 decides to remove from the remaining game stone pile
validInputPlayerOne = true;
gameStonePile = gameStonePile - playerOneRemoval;
// Record that Player 1 was the most recent player that removed stones from pile
lastPlayerTurn = namePlayerOne;
// When the stone pile reaches zero, determine Player 1 as winner
if (gameStonePile == 0) {
playerOneWins = playerOneWins + 1;
System.out.println();
System.out.println(namePlayerOne + " wins round #" + numRounds + "! The current score is:");
System.out.println();
System.out.println(namePlayerOne + ": " + playerOneWins);
System.out.println(namePlayerTwo + ": " + playerTwoWins);
}
} while (playerOneRemoval >= 1 && playerOneRemoval <= playerRemoveLimit && validInputPlayerOne == false);
}
if (gameStonePile != 0) {
do {
validInputPlayerTwo = false;
// Player Two's turn
System.out.println(namePlayerTwo + ", it is your turn. Please enter the amount of stones you want to"
+ " remove. In the stone pile currently, there are " + gameStonePile + " stone(s).");
// Get amount Player 2 wants to remove from current/remaining stone pile
playerTwoRemoval = keyboard.nextInt();
while (playerTwoRemoval < 1 || playerTwoRemoval > playerRemoveLimit || playerTwoRemoval > gameStonePile) {
System.out.println("Invalid input. Please try again.");
playerTwoRemoval = keyboard.nextInt();
}
validInputPlayerTwo = true;
// Subtract amount Player 2 decides to remove from the remaining game stone pile
gameStonePile = gameStonePile - playerTwoRemoval;
// Record that Player 1 was the most recent player that removed stones from pile
lastPlayerTurn = namePlayerTwo;
if (gameStonePile == 0) {
playerTwoWins = playerTwoWins + 1;
System.out.println();
System.out.println(namePlayerTwo + " wins round #" + numRounds + "! The current score is:");
System.out.println();
System.out.println(namePlayerOne + ": " + playerOneWins);
System.out.println(namePlayerTwo + ": " + playerTwoWins);
}
} while (playerTwoRemoval >= 1 && playerOneRemoval <= playerRemoveLimit && validInputPlayerTwo == false);
}
// When the user-requested # of rounds have been reached and game-stone pile reaches zero from
// very last round, display end of game message
if (numRounds == userGameRounds && gameStonePile == 0) {
numRounds = 0;
playRounds = false;
System.out.println();
System.out.println("Hooray! The game has finished!");
// Determine the best player so far and their # of wins
if (playerOneWins > playerTwoWins) {
System.out.print(namePlayerOne + " is the best player so far with " + playerOneWins + " win(s).");
}
else if (playerTwoWins > playerOneWins) {
System.out.print(namePlayerTwo + " is the best player so far with " + playerTwoWins + " win(s).");
}
else{
System.out.print(namePlayerOne + " and " + namePlayerTwo + ", it looks like it's a draw!");
}
}
// Once game between two players finishes, ask user how they want to proceed based on three
// options
if (numRounds == 0){
System.out.println();
System.out.println("How would you like to proceed? You have three options. Enter '1' if you would like to"
+ " play another game with the same players. Enter '2' if you want to exit the game."
+ " Enter '3' to play another game with different players.");
// Get user-input of how they want to proceed
proceedChoice = keyboard.nextInt();
// Check for valid input
while (proceedChoice <1 || proceedChoice >3){
validProceed = false;
System.out.println("Invalid input. Please try again.");
proceedChoice = keyboard.nextInt();
}
validProceed = true;
// Loop back accordingly to if the same players want to play a new game, different players
// want to play a new game, and exit the game if user chooses to do so
if (proceedChoice == 1) {
playSameGame = true;
}
else if (proceedChoice == 2) {
playDifferentGame = true;
}
else if (proceedChoice == 3){
playDifferentGame = false;
}
}
}
}
} while (playSameGame == true);
} while (playDifferentGame == true);
keyboard.close();
} // main method
} // Strategy Game class
I know this issue has to do something with my loops, but I can't seem to figure it out. I would appreciate some help. Thanks!
Your loop looks for your playSameGame variable to be false for it to exit. But it is never set to false anywhere in your code. So it will repeat forever.
I agree with IanGabes comment for writing good stack overflow questions, but also just for learning how to debug these things on your own. The best way is to make your code as simple as possible when you have a problem.
Help, please.
This code does't work:
for (i = 0; i == userWhoIsInLineArray.GetNumberOfUsersOnline() - 1; i++) {
Log.d("DATA-----|", "UserName- "
+ userWhoIsInLineArray.GetUserName(i)
+ " UserHref- "
+ userWhoIsInLineArray.GetUserAccountHref(i));
}
When I write this one, all work!
while(i != userWhoIsInLineArray.GetNumberOfUsersOnline() - 1) {
Log.d("DATA-----|", "UserName- "
+ userWhoIsInLineArray.GetUserName(i)
+ " UserHref- "
+ userWhoIsInLineArray.GetUserAccountHref(i));
i++;
}
Why is happening?
I doubt you meant to use equality in your for loop test for continuance?
This bit:
i == userWhoIsInLineArray.GetNumberOfUsersOnline()-1
Perhaps you meant another comparison operator?
You should write as:
for (i = 0; i < userWhoIsInLineArray.GetNumberOfUsersOnline(); i++) {
Log.d("DATA-----|", "UserName- "
+ userWhoIsInLineArray.GetUserName(i)
+ " UserHref- "
+ userWhoIsInLineArray.GetUserAccountHref(i));
}
Only when the second sentence of for-clause is true, for-block is executed. So, when the variable i is smaller than userWhoIsInLineArray.GetNumberOfUsersOnline(), it must be true.
cf 1. i == userWhoIsInLineArray.GetNumberOfUsersOnline() means only when variable i equals userWhoIsInLineArray.GetNumberOfUsersOnline() it is true. Unless userWhoIsInLineArray.GetNumberOfUsersOnline() is 0, it results false for the first loop.
cf 2. In the same sence your while-loop is better to rewrite as:
int i = 0;
while (i < userWhoIsInLineArray.GetNumberOfUsersOnline()) {
Log.d("DATA-----|", "UserName- "
+ userWhoIsInLineArray.GetUserName(i)
+ " UserHref- "
+ userWhoIsInLineArray.GetUserAccountHref(i));
i++;
}
I need to find and display the sum of the cubes of the first n natural numbers and with what code i have currently i can only seem to print up to the range that i want.
Being the max is 20 and it prints the cubes of my number up to 20. The loops that i write for the sum do not work and normally crash the program.
Any help or ideas on how to make it so the program only cubes up to the number that is input and then sum those cubes would be appreciated, please keep it simple.
public class MyIntNumberr
{ // construct a myintnumber with one instance field n
public MyIntNumberr(int n)
{
number = n;
}
public void calcCubeAndSum(int num)
{
if (num < 0)
{
System.out.println("that integer is invalid please try again");
System.exit(0);
}
while (num >= 1 && num <= 20)
{
System.out.println(" " + num + " " + Math.pow(num, 3));
num = num + 1;
}
}
// instance fields
private int number;
}
import javax.swing.JOptionPane;
public class MyIntNumberTestt
{
public static void main(String[] args)
{
int number, num;
String input = JOptionPane.showInputDialog("enter a value to cube and gather the sum of");
num = Integer.parseInt(input);
MyIntNumberr richard = new MyIntNumberr(num);
richard.calcCubeAndSum(num);
System.exit(0);
}
}
I don't see in your code where you accumulate the sum of the cubes...
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws Exception {
System.out.print("Enter a value to cube and gather the sum of: ");
int num = input.nextInt();
calcCubeAndSum(num);
}
private static void calcCubeAndSum(int num) {
if (1 <= num && num <= 20) {
int sum = 0;
while (num <= 20) {
// Calculate the cube
int cube = num * num * num;
// Accumulate the cube into a sum
sum += cube;
// Display current result
System.out.println("Current number: " + num + "\tCubed: " + cube + "\tCurrent Sum: " + sum);
// Go to the next number
num++;
}
// Display Total Sum
System.out.println("Total Sum: " + sum);
} else {
System.out.println("That integer is invalid please try again");
}
}
Results:
HERE IS A SIMPLE WAY TO FIND N NATURAL NUMBERS USING PYTHON
hope you all like it....
n = int(input("Enter the value of n:"))
for i in range (1,n+1):
print(i)
ANSWER
Enter the value of n:10
1
2
3
4
5
6
7
8
9
10
Been working on a program that is suppose to Loop and display 13 times. Here is my code
{
var count;
var user_Input;
var output_msg;
var cel;
count = 0;
do
{
user_Input = get_integer("Temperature conversion","");
count = count + 1;
cel = user_Input * 9/5 +32;
user_Input = user_Input +10;
output_msg =(string(count) + "Celsius" + string(user_Input) + " = Farenheit " + string(cel));
show_message(output_msg);
}
until (count == 13)
}
What It Does is it Displays the loop each time I hit enter instead of showing all 13 at once also if i enter 10 for example each time it loops its suppose to add 10 from the last loop.
eg. 1. Celsius 10 = Farenheit (answer here)
..... 2. Celsius 20 = Farenheit (answer Here)
......13. Celsuis 130 = Farenheit "" if some one could walk me through and help me that would be great
What you'll have to do is :
move the dialog box show_message outside the loop, well, after the Do loop to be precise. Then, it will be displayed only at the end of the loop, while the get_integer dialog box will of course wait for the user to enter a value.
move the get_integer aswell outside the loop, right before it. User will just have to input value once. If you put it inside the loop, you'll be asked to enter a value 13th times...
append the resulting calculations to the message to be displayed contained in output_msg to itself, with the line feed "#" at the end.
{
var count = 0;
var user_Input;
var output_msg = "";
var cel;
count = 0;
user_Input = get_integer("Temperature conversion","");
do
{
count = count + 1;
cel = user_Input * 9 / 5 + 32;
user_Input = user_Input + 10;
output_msg = (output_msg + string(count) + ". Celsius" + string(user_Input) + " = Farenheit " + string(cel) + "#");
}
until (count == 13)
show_message(output_msg);
}
For clarity, I've initialized some variables initial values.
Your issue is not a code issue, it's a logic issue (except for the line feed) Everything inside a loop, (Do, While) will be executed on every iteration. If you don't want something to be executed, you must either move it outside the loop (before/after), or use a condition check.