I am working in java and I want my loop to run for as long as there are projects as specified by the user. As of now, the code runs through for one iteration, and reads the results of the one loop, but it won't continue any further.
If the user says there are 3 projects, I want the code to run through the loop 3 times and tell me the total of each project. Right now, it tells me the total of 1 project whether I specify the number of projects are 1 or 5.
double projectBoardFootage = 1.0;
double projectBoardFootageTotal = 0.0;
int i = 0;
System.out.println("How many projects do you want to estimate?");
int numberOfProjects = scan.nextInt();
for(i = 0; i < numberOfProjects; ++i) {
while (projectBoardFootage > 0) {
System.out.println("Enter your board footage for Project #" + (i + 1) + " (0 to exit)");
projectBoardFootage = scan.nextDouble();
projectBoardFootageTotal += projectBoardFootage;
}
System.out.println("The raw board footage for Project #" + (i + 1) + " is: " + projectBoardFootageTotal);
}
Perhaps you want to reinitialize the total board footage to clear the previous iteration count?
for(i = 0; i < numberOfProjects; ++i) {
projectBoardFootageTotal = 0.0;
while (projectBoardFootage > 0) {
System.out.println("Enter your board footage for Project #" + (i + 1) + " (0 to exit)");
projectBoardFootage = scan.nextDouble();
projectBoardFootageTotal += projectBoardFootage;
}
System.out.println("The raw board footage for Project #" + (i + 1) + " is: " + projectBoardFootageTotal);
}
The problem in your code is that you're using the variable projectBoardFootage to terminate the loop.
Think about what happens when this value is set to 0.
We exit the while-loop, and the value never gets changed again. So from that point on, every iteration will end immediately.
The better solution is to do something like this:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many projects do you want to estimate?");
int numberOfProjects = scan.nextInt();
for(int i = 0; i < numberOfProjects; ++i) {
foobar(scan, i+1);
}
}
private static void foobar(Scanner scan, int projectNr)
{
boolean wantsToQuit = false;
double projectBoardFootageTotal = 0;
while (!wantsToQuit) {
System.out.println("Enter your board footage for Project #" + projectNr + " (q to exit)");
String tmp = scan.next();
if(tmp.equalsIgnoreCase("q"))
wantsToQuit = true;
else
projectBoardFootageTotal += Double.parseDouble(tmp);
}
System.out.println("The raw board footage for Project #" + projectNr + " is: " + projectBoardFootageTotal);
}
This code also ensures the user enters a more sensible keycode than '0' to quit.
Related
I can't figure out how to correctly write my for loop statement that will give me the correct score. I bolded the code that is what I can't figure out how to write correctly. Anytime I run my program I end up with the first result of (rslt < 3) no matter what numbers I enter.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String options[] = {
"mild or spicy",
"tea or coffee",
"breakfast or " +
"brunch",
"summer or winter",
"paper or plastic"
};
int answers[] = new int[options.length];
String result[] = new String[answers.length];
boolean bool = true;
while (true) {
for (int i = 0; i < options.length; i++) {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 1] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 2] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 3] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 4] + "?");
answers[i] = scanner.nextInt();
break;
}
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
int rslt = getScore(result);
if (rslt < 3)
System.out.println("You prefer life to be calm and organized");
else if (rslt > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
int out = scanner.nextInt();
if (out == 0)
bool = false;
if (!bool)
System.exit(0);
}
}
static int getScore(String[] result) {
int score = 0;
for (int i = 0; i < result.length; i++) {
switch (result[i]) {
case "spicy":
score++;
break;
case "coffee":
score++;
break;
case "breakfast":
score++;
break;
case "winter":
score++;
break;
case "paper":
score++;
break;
}
}
return score;
}
}
I have modified your code according to my understanding of the code.
It works just exactly like you may have wanted.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[][] options = {
{"mild", "spicy"},
{"tea", "coffee"},
{"brunch", "breakfast"},
{"summer", "winter"},
{"plastic", "paper"}
};
int[] answers = new int[options.length];
do {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i][0] +
" or " + options[i][1] + "?");
answers[i] = scanner.nextInt();
}
int result = getScore(answers);
if (result < 3)
System.out.println("You prefer life to be calm and organized");
else if (result > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
} while (scanner.nextInt() != 0);
}
static int getScore(int[] answers) {
int score = 0;
for (int answer : answers) if (answer == 1) score++;
return score;
}
}
To Fix Your Code
In the first for-loop, you are supposed to loop through the options array. But somehow you unfold the loop within the loop body. To prevent the whole thing loop again, you break the loop immediately. To fix the first loop, write it like this instead. Properly loop through each element, no need to unfold it, no need to break it.
System.out.println("Enter 0 for the preference on the left\n" + "Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
}
In the second loop, you are supposed to retrieve the selected string from answers and write the string to results. Without modifying your data structure, this can be achieved by using split(" or ") on the option, which gives you an array of string which you can use the answer as index to access. Note that this does not prevent array index out of bound exception if user enter anything other than 0 or 1, which you should totally do, but is out of scope of this question.
for (int i = 0; i < answers.length; i++) {
result[i] = options[i].split(" or ")[answers[i]] ;
}
And there you go.
To Solve Your Task
Alternatively, redesigning the data structure and logic to get rid of the unnecessary string manipulation and comparison is more ideal. You don't even need the result and answers array, simply add up the user input will do (if the user follows your instruction)
int rslt = 0;
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
rslt += scanner.nextInt();
}
Inside the loop, you continue assigning the result to the same index in the answers list, rather than assigning the result to another index for each input. Because you are not iterating anything, you don't even need the loop. Replace the entire while loop with the code below. Please upvote and accept answer if it solves/helps you with your problem.
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[0] + "?");
answers[0] = scanner.nextInt();
System.out.println("Do you prefer " + options[1] + "?");
answers[1] = scanner.nextInt();
System.out.println("Do you prefer " + options[2] + "?");
answers[2] = scanner.nextInt();
System.out.println("Do you prefer " + options[3] + "?");
answers[3] = scanner.nextInt();
System.out.println("Do you prefer " + options[4] + "?");
answers[4] = scanner.nextInt();
Also, please note this:
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
won't work. Instead of result[i] = [answers[i]];, do result[i] = Integer.parseInt(answers.get(i)).
This is part causing the unexpected behaviour: result[i] = [answers[i]];
From what I understood, you want to implement this:
For each option, store the user choice like 0 or 1, 0 for left, 1 for right
For each user choice, store the string value of the choice, i.e., for the 1st question if the user inputs 0, mild should be captured
Calculate scores by comparing string value of user input against a branching construct, switch case here
The problem is in step 2, the current code result[i] = [answers[i]]; does not express this operation properly.
answers[i] stores the user choice 0 or 1, step 1 operation. So to convert it to the corresponding choice in string step 2 operation, something like this should be done
(options[i].split(" or "))[answers[i]]
Explanation:
Pick up the complete string for each answer
Divide the string into two parts(array with 2 indexes 0 and 1), left and right, using a delimiter, " or " in this case
pick up the left or right based on the value stored in answers[i](the user input)
This should let the code behave as expected :)
There are other aspects that can be improved in the code though, as others have already suggested.
Im trying to stop a loop that takes integers after typing in the console "End", but i cant seem to find a way to do it.
Scanner scan = new Scanner(System.in);
int bottles = Integer.parseInt(scan.nextLine()) * 750;
int cnt = 1;
int platesTotal;
int potsTotal;
int nrPlates = 0;
int nrPots = 0;
while(true){
int plates = scan.nextInt();
platesTotal = plates * 5;
if(cnt%3==0) {
int pots = scan.nextInt();
nrPots = nrPots + pots;
nrPlates = nrPlates + pots;
potsTotal = pots * 15;
if (bottles < potsTotal + platesTotal) {
System.out.println("Not enough detergent, " + (potsTotal + platesTotal - bottles) + " ml. more necessary!");
break;
}
else
if(bottles >= potsTotal + platesTotal) {
String enough = scan.nextLine();
if (enough.equals("End")) {
if (bottles >= potsTotal + platesTotal) {
System.out.println("Detergent was enough!");
System.out.println(nrPlates + " dishes and " + nrPots + "pots were washed.");
System.out.printf("Leftover detergent %d ml.", bottles - potsTotal - platesTotal);
break;
}
}
}
}
cnt++;
}
after inputting the string ("End"), it needs to show me the total of dishes and pots, and how much detergent it has left, and if the required amount of detergent is more than the available amount, it needs to show me how much more is needed.
Try this String enough = scan.next(); instead of scan.nextLine();
I would suggest printing messages to console to confirm to the user you want input. Otherwise, it'll just show a blank window. I would also suggest you define a boolean variable to escape the while loop while switching your enough to .next rather than .nextLine. This way, you redefine your boolean as false to break the while loop while also getting the output you desire to control your program output a bit more. This compiled with all entries of 1:
package com.climatedev.test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("How many bottles?");
Scanner scan = new Scanner(System.in);
int bottles = scan.nextInt() * 750;
int cnt = 1;
int platesTotal;
int potsTotal;
int nrPlates = 0;
int nrPots = 0;
boolean run = true;
while(run){
System.out.println("How many plates?");
int plates = scan.nextInt();
platesTotal = plates * 5;
if(cnt%3==0) {
int pots = scan.nextInt();
nrPots = nrPots + pots;
nrPlates = nrPlates + pots;
potsTotal = pots * 15;
if (bottles < potsTotal + platesTotal) {
System.out.println("Not enough detergent, " + (potsTotal + platesTotal - bottles) + " ml. more necessary!");
break;
}
else
if(bottles >= potsTotal + platesTotal) {
System.out.println("Would you like to end the program? (Enter End)");
String enough = scan.next();
if (enough.equals("End")) {
if (bottles >= potsTotal + platesTotal) {
System.out.println("Detergent was enough!");
System.out.println(nrPlates + " dishes and " + nrPots + "pots were washed.");
System.out.printf("Leftover detergent %d ml.", bottles - potsTotal - platesTotal);
run = false;
System.out.println("Goodbye");
break;
}
}
}
}
cnt++;
}
}
}
I also changed your bottles slightly to use nextInt, though that depends on your use. If you're thinking the end user might type something like "The number of bottles are..." that'll be better, but otherwise why not use a simpler nextInt call?
if you want to use a scanner object for both strings and numbers you must parse the number:
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
int num = Integer.parseInt(scanner.nextLine());
or you can have two scanners(one for strings and another for numbers):
Scanner strScanner = new Scanner(System.in);
Scanner numScanner = new Scanner(System.in);
String str = strScanner.nextLine();
int num = numScanner.nextInt();
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();
I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.
I'm completely new to coding and I was wondering if you guys can help me. This is part of a code in which you battle a vampire, RPG style. My program does not loop back to my characters turn after I set the turn number to one near the bottom of the code, why is this?
/**
* Created by f on 7/30/2014.
*/
import java.util.Scanner;
import java.util.Random;
public class rpgBattle {
public static void main(String[] args) {
// Declarations
int charHp = 3941;
int enemyHp = 5200;
String charName;
int numDmg;
int dmgMultiplier = 1;
String playerInputSt;
int playerInput;
int turn = 1;
int miss;
//Processes
Scanner user_input = new Scanner(System.in);
System.out.println("Enter your name.");
charName = user_input.next();
System.out.println();
System.out.println("A vampire emerged!");
do {
System.out.println();
System.out.println(charName + "'s HP: " + charHp + "/3941");
System.out.println("The Vampire's HP: " + enemyHp + "/5200");
System.out.println("What will you do?");
System.out.println("Enter the number corresponding to the action you would like to perform.");
System.out.println("1. Attack");
System.out.println("2. Defend");
System.out.println(turn);
playerInputSt = user_input.next();
playerInput = Integer.parseInt(playerInputSt);
if (playerInput == 1) {
Random rand = new Random();
miss = rand.nextInt(19);
if (miss == 0) {
System.out.println();
System.out.println("The Vampire protected itself.");
numDmg = 0;
} else {
numDmg = rand.nextInt(100) + 550;
}
enemyHp = enemyHp - numDmg / 1;
System.out.println();
System.out.println(charName + " attacks!");
System.out.println("The Vampire took " + numDmg / dmgMultiplier + " damage!");
turn = 2;
} else if (playerInput == 2) {
System.out.println();
System.out.println(charName + " guards");
System.out.println(charName + " recovered 394 HP!");
charHp = charHp + 394;
dmgMultiplier = 2;
turn = 2;
};
} while (charHp > 0 && enemyHp > 0 && turn !=2);
do {
Random rand = new Random();
miss = rand.nextInt(19);
if (miss == 0) {
System.out.println();
System.out.println(charName + " braced himself.");
numDmg = 0;
} else {
numDmg = rand.nextInt(500) + 200;
charHp = charHp - numDmg / dmgMultiplier;
}
System.out.println("The Vampire attacks!");
System.out.println(charName + " took " + numDmg / dmgMultiplier + " damage!");
dmgMultiplier = 1;
turn = 1;
} while (turn == 2);
}
}
It will never end because in the top level loop, the condition to get out is that the character's health drops below 0. However, you are never decreasing his HP. You are only decreasing the vampire's HP, but not the character. If you want the game to end, make the vampire attack the character too. That way, in some point his HP will drop below 0 and the game will end.
However, to make it more realistic, you should make the game end when the HP of the vampire OR the character are 0, and not when both of them are below 0. To achieve that, instead of using 3 loops, use 2, but changing the condition so that when either one of them has no HP, it will end:
do {
do {
...
} while (turn == 1);
} while (charHp > 0 && enemyHp > 0);
Without spending too much time analyzing all of your code, it looks like you have nested a Do..While Loop for charHp and a Do..While Loop for enemyHp. I think you need only one Do..While Loop that loops until either charHp or enemyHp is zero.
do {
do {
//.... Lots of code removed for brevity in the answer .....
} while (turn == 1);
} while ((enemyHp > 0) && (charHp > 0));
or should it be like this, with only one Do..While Loop
do {
//.... Lots of code removed for brevity in the answer .....
} while ((turn == 1) && (enemyHp > 0) && (charHp > 0));
What is the purpose of the variable turn ? Once a valid value is entered its value will be 2 untill the end of the game so the inner while will always loop only once.
But the the code will still be executed each time as the outer loops continue to loop until a score drops to 0.
If you want to know the number of turns you are playing, you should increase turn:
turn++;
and remove the most inner while loop.
If you want to loop until the user has entered a valid value, you should initialise turn at the beginning of the most inner loop:
turn=1;
good luck.