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.
Related
I want to make the queue list only show 10 songs at a time, because right now the bot crashes and says that every embed field can only have 1024 characters.
I've put the most important part below, you can find the rest here.
exports.playQueue = (guildId, channel) => {
if (!guilds[guildId] || !guilds[guildId].nowPlaying) {
var embed = new Discord.RichEmbed()
.setColor(9955331)
.setDescription(":mute: Not Playing");
channel.send(embed);
return;
}
var g = guilds[guildId];
var q = "";
var i = 1;
let ytBaseUrl = "https://www.youtube.com/watch?v=";
g.playQueue.forEach((song) => {
let ytLink = ytBaseUrl + song.id;
let title = song.title;
if (title.length > 30) title = title.substring(0, 19) + "... ";
q += "`" + i++ + "`. ";
q += `[${title}](${ytLink}) | `;
q += "`" + song.length + "`\n";
});
let currSong = g.nowPlaying.title;
if (currSong.length > 30) currSong = currSong.substring(0, 19) + "... ";
var cs = `[${currSong}](${ytBaseUrl+g.nowPlaying.id}) | `;
cs += "`" + g.nowPlaying.length + "`";
var embed = new Discord.RichEmbed()
.setColor(9955331)
.addField(":musical_note: Now Playing", cs);
if (g.loop) embed.setFooter("🔁 Looping playlist");
if (q != "") embed.addField(":notes: Play Queue", q);
channel.send(embed);
}
I would solve the problem by building a queue that goes from the first to the tenth song
// I chose a for loop just because I can break out of it
// This goes on until it reaches the end of the queue or the tenth song, whichever comes first
for (let i = 0; i < g.playQueue.length && i < 9; i++) {
let song = g.playQueue[i];
// This is your part
let ytLink = ytBaseUrl + song.id;
let title = song.title;
if (title.length > 30) title = title.substring(0, 19) + "... ";
// Instead of directly adding the next line to q, I store it in another variable
let newline = "";
newline += "`" + (i+1) + "`. ";
newline += `[${title}](${ytLink}) | `;
newline += "`" + song.length + "`\n";
// If the sum of the two lengths doesn't exceed the 1024 chars limit, I add them together
// If it is too long, I don't add it and exit the loop
if (q.length + newline.length > 1024) break;
else q += newline;
}
This should fix it, since q should not exceed 1024 characters. This is a simple but effective solution in my opinion.
Feel free to let me know if something doesn't work properly ;)
This is my first post so don't go rough on me if I happened to skip something I should have mentioned.
I am working on a program that simulates a tennis championship, and the outcome of an individual match via a rand() function to distribute the points among the 2 players currently in said match.
I have scanned the program and did my best to fix the issues but there is still a problem I can not fix, it is the function that determines the outcome of the matches. The problem is that the function returns strange values, nothing they should look like.
I first thought there is a problem with the declaration of the variables and the way I did operations with them but that did not seem to be the case, so I ran out of ideas and come to you.
Here is the code:
jucatori meci(jucatori jucator1,jucatori jucator2 )
{
int u =0; //scor jucator 1
int o=0; //scor jucator 2
int p; //aux j1
int l; //aux j2
int i;
do
{
//first loop, where player 1 serves
p= rand() % jucator1.sansaServire; //generate a number for player1
l= rand() % jucator2.sansaPrimire; //generate a number for player2
if(l>p)
{
o=o+1;
do
{
//going into the second loop, in this loop, here, player 2 serves
p = rand() % jucator1.sansaPrimire;
l = rand() % jucator2.sansaServire;
if(p>l) u = u+1;
if(l>p) o = o+1;
else break; //iese din bucla 2, juc1 va servi iarasi
}while(l>p);
}
else if(p>l) u = u+1;
}while(u + o < 51); //inchidem prima bucla
if(u > o && u - o > 10)
{
jucator1.meciurijucate++;
jucator2.descalificat = 1;
jucator1.scor1 = u;
jucator1.scor2 = o;
return jucator1;
} //return player 2, add 1 to the number of matches played and mark player 1 as out of the game
else if(o > u && o - u > 10)
{
jucator2.meciurijucate++;
jucator1.descalificat = 1;
jucator2.scor1 = o;
jucator2.scor1 = u;
return jucator2;
}//return player 1, add 1 to the number of matches played and mark player 2 as out of the game
else return meci(jucator1,jucator2); //call function again if the match is a draw
}
I will provide the full program if needed, just thinking that it would be pretty bulky to post the whole thing.
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.
I'm trying to separate / explode an String to do something with it later on.
The input string is this:
1_2_3_2_2
The function I'm calling with the above value as parameter:
void parseXString(String value){
int amountX = (value.length() / 2) + 1;
int seperatorIndex = value.indexOf('_');
int secondSeperator = 0;
for(int i = 0; i < amountX; i++){
String xPoint = "";
if(i == 0){
xPoint = value.substring(0, seperatorIndex);
}else{
xPoint = value.substring(seperatorIndex + 1, secondSeperator);
}
sendMessage((String)i + " X = " + xPoint + " || SEP: " + (String)seperatorIndex + " / " + (String)secondSeperator );
seperatorIndex = value.indexOf("_", seperatorIndex + 1);
secondSeperator = value.indexOf("_", seperatorIndex + 1);
}
sendMessage("Last X = " + value.substring(seperatorIndex + 1));
}
The sendMessage function will shout the value back to the operating Java application. The output I get is this:
0 X = 1 || SEP: 1 / 0
1 X = 3 || SEP: 3 / 5
2 X = 2 || SEP: 5 / 7
3 X = 2 || SEP: 7 / -1
4 X = 1 || SEP: -1 / 1
Last X = 2_3_2_2
As you can notice, on the second iteration there should be an return of the value 2 instead of an 3.
I think there's something wrong with the seperatorIndexes, but I'm out of the blank right now (working on this way to long).
So my question is very simple. Why doesn't I get the right value back / how can I fix that?
Your error is that you increase seperatorIndex in the first iteration. Therefore, seperatorIndex is 3 in your second iteration.
You should put the part where you increment seperatorIndex into the else part of your if(i == 0) condition. When doing this, you also have to increment secondSeperator in the if part of your condition.
i got into this simple program in c programing, the program is simply reversing any input number by user, using a while loop, i dont know if its okay to post such a question but i didnt realy understood how the while loop works
int n, reverse = 0;
printf("Enter a number to reverse\n");
scanf("%d",&n);
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
printf("Reverse of entered number is = %d\n", reverse);
i would be so thankfull if anyone could explain it to me
while(condition is true)
{
// Do stuff.
// Normally, but not always, the "stuff" we're doing is something that modifies
// the condition we're checking.
}
So in your case as long as the content of n is not equal to 0, you will continue to execute the loop. If 0 is entered in the scanf() the loop will be skipped altogether.
At each iteration of your loop you're using the property of integer division to make the value of n smaller by a factor of 10. ie:
n = 541
n = n / 10 = 541/10 = 54
n = n / 10 = 54/10 = 5
n = n / 10 = 5/10 = 0
So n will eventually be 0 and the loop will exit.