Infinitely Looping if statement - java

First: I keep running into an infinite loop in the following code. The code is built so that you enter 8 numbers between 1 and 10. It proofs that these numbers are between 1 and 10. Then the second proof is that these 8 numbers added together equal 60. I'm having trouble with the end if else statement. If the total of the numbers is 60 it works fine and gives the print out but if it gets stopped at the if statement it infinitely prints the "You've entered the wrong total number" printout as well as an ever increasing total number of points. Am I missing something easy like a parenthesis or something?
Secondly: How can I loop back to the original entering of values if the total is not 60 and start the whole process over?
public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "\n" + "Mid Range" + "\n" + "Three Point" + "\n" + "Free Throw" + "\n" + "Offensive Rebound" + "\n" + "Defensive Rebound" + "\n" + "Assist" + "\n" + "Steal" + "\n");
while (attribute <= 7) {
int attributeValue = input.nextInt();
if (attributeValue >= 1 && attributeValue <= 10 ) {
lebronJamesAttributes[attribute] = attributeValue;
attribute++;
}
else {
System.out.println("The attribute value you have selected is out of range. Select again.");
}
}
int jamesTotalQuarter = 0;
while (jamesTotalQuarter != 60){
for (int jamesTotalQ1 : lebronJamesAttributes){
jamesTotalQuarter += jamesTotalQ1;
}
if (jamesTotalQuarter != 60) {
System.out.println("You have entered the wrong total number of attribute points. Please enter a total of 60 attribute points between the 8 characteristics.");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");
}
else {
System.out.println("Close Range" + lebronJamesAttributes[0] + "\n" + "Mid Range" + lebronJamesAttributes[1] + "\n" + "Three Point" + lebronJamesAttributes[2] + "\n" + "Free Throw" + lebronJamesAttributes[3] + "\n" + "Offensive Rebound" + lebronJamesAttributes[4] + "\n" + "Defensive Rebound" + lebronJamesAttributes[5] + "\n" + "Assist" + lebronJamesAttributes[6] + "\n" + "Steal" + lebronJamesAttributes[7] + "\n");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");}
}
}
}

Let me know if the following code solves your problem. Have not tested it, but it should just work fine now. Get the logic and fix it yourself incase of errors.
public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
While(true){ // keeps it in a loop forever and only a "break" statement can stop it
//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "\n" + "Mid Range" + "\n" + "Three Point" + "\n" + "Free Throw" + "\n" + "Offensive Rebound" + "\n" + "Defensive Rebound" + "\n" + "Assist" + "\n" + "Steal" + "\n");
while (attribute <= 7) {
int attributeValue = input.nextInt();
if (attributeValue >= 1 && attributeValue <= 10 ) {
lebronJamesAttributes[attribute] = attributeValue;
attribute++;
}
else {
System.out.println("The attribute value you have selected is out of range. Select again.");
}
}
int jamesTotalQuarter = 0;
for (int jamesTotalQ1 : lebronJamesAttributes){
jamesTotalQuarter += jamesTotalQ1;
}
if (jamesTotalQuarter != 60) {
System.out.println("You have entered the wrong total number of attribute points. Please enter a total of 60 attribute points between the 8 characteristics.");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");
continue; // loop execution starts from the beginning and your program gets fresh inputs.
}
else {
System.out.println("Close Range" + lebronJamesAttributes[0] + "\n" + "Mid Range" + lebronJamesAttributes[1] + "\n" + "Three Point" + lebronJamesAttributes[2] + "\n" + "Free Throw" + lebronJamesAttributes[3] + "\n" + "Offensive Rebound" + lebronJamesAttributes[4] + "\n" + "Defensive Rebound" + lebronJamesAttributes[5] + "\n" + "Assist" + lebronJamesAttributes[6] + "\n" + "Steal" + lebronJamesAttributes[7] + "\n");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");}
break; // breaks from the loop on correct input
}
}
}

Related

Is there anyway to format this? The code already runs fine but the formatting will run if the value is too big

I know that I can just use printf to format it but printf is used to print. I want to use the formatting to store the data then call the data to print it outside the do while loop.
#Override
public String toString() {
Scanner input = new Scanner(System.in);
String enter = "", data = "";
double totalCommission = 0.0;
DecimalFormat df = new DecimalFormat();
do {
setTransaction();
setSalesNum();
setName();
setAmount();
setCommission();
setRate();
do {
//prompt user to enter another
System.out.println("Would you like to enter another? [Y/N]");
boolean error = false;
//error prompt if y or n is not entered
enter = input.next();
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
error = true;
System.out.println("Invalid input! Please enter again.\n Would you like to enter another student's mark? [Y/N]");
} else {
error = false;
}
} while (false);
//setting the decimal places
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
//transaction details saved here
data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n";
totalCommission = totalCommission + getCompute();
} while (enter.equalsIgnoreCase("Y"));
System.out.println("Sales\tCommission");
System.out.println("TNO#\tSALESNO#\tNAME\t\tAMOUNT\t\t" + " " + "COMM RATE\tCOMMISSION");
return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
}
So what I wanted to do is for this part data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n"; to be formatted inside while (enter.equalsIgnoreCase("Y")); then send data here: return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
I'm sorry but I don't understand what you want to achieve. You may add an input and desired output example.
First of all:
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
if (!(enter.equalsIgnoreCase("n")|| enter.equalsIgnoreCase("y"))) {
You talked about print so you may want to take a look into: https://www.javatpoint.com/java-string-format
Because you mentioned String.format already I guess I misunderstood your question. If you reply back to me I will try to help you.
You wrote that you want to store your data inside that while loop and return it later. In this case, I would add every data to a list and return this list.

Java while loop not terminating despite condition being false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I want to create a game called Crap. The problem that I am facing is that the main while loop does not end despite the condition being set to false (by user inputing "no" when asked if they want to conitnue playing). What is the problem here? Comments are inserted where I think the problem is.
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (proceed != "no"){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
You are using the wrong operator. != checks if the two objects on left and right side are the the same (e.g. two variables reference the same object in memory).
You must write while (! "no".equals(proceed) ).
I did not write while (! proceed.equals("no") ) on purpose because if the string is null then you would get a NullPointerException.
I am not sure if Scanner.readLine() does ever return a null string, so it may make no difference here. But writing it in the "reverse" way as in my first example is more safely in general.
For a String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .
You have to use .equals(String) to compare Strings, like so:
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (!proceed.equals("no")){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}

Displaying number of times a character is in a string

I need to print the amount of times an input character appears in the string. It runs and works for all tests, however when a character appears only 1 time it prints "1 times" instead of "1 time" like expected, and i am unsure of how to add this into my code. It has to be when count is equal to 1 the outprint changes from times to time. I am lost.
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
Expected to
You should add a condition for the same instead of printing the static string "times" as below:
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
String str = (count==1)?"time":"times";
System.out.println("The letter '" + letter + "' appears " + count + str + " in the string " + "\"" + input + ".\"");
Maybe try something like this
String plural = (count == 1) ? "" : "s";
System.out.println("The letter '" + letter + "' appears " + count + " time" + plural + "in the string " + "\"" + input + ".\"");
I would use an if statement to determine how many times this specific letter appears in your string. Also, since first character is charAt(0), the last character should be charAt(s.length()-1);.
for( i = 0; i < (input.length()-1); i ++){
if (input.charAt(i) == letter)
count = count + 1;
} //end of your for loop
if (count == 1){
System.out.println("The letter '" + letter +
"' appears " + count + " time in the string " + "\"" + input + ".\"");
}
else{
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
}

if/else statement inside of a while loop

I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}

What is wrong with my loop

I'm a beginner Java student trying to make this code list the amount saved and interest for 8 years. I'm trying to use a for loop for it. It calculates the interest but only lists it for 1 year. Would appreciate any help solving this problem.
import javax.swing.JOptionPane;
import java.text.*;
public class RetirementGoal3
{
private static DecimalFormat percentFormat = new DecimalFormat("###.##%");
private static DecimalFormat moneyFormat = new DecimalFormat("$###,###,###.00");
private static double interest;
private static double saveAmount;
private static double total;
private static int Max_Year = 8;
private static int year;
private static double totalSave;
private static double totalInterest;
public static void main(String[] args)
{
calculateR();
}
public static double calculateR()
{
String result = JOptionPane.showInputDialog(null, "Enter how much money you can save annually.");
if(result != null)
saveAmount = Double.parseDouble(result);
String result1 = JOptionPane.showInputDialog(null, "Enter your interest rate(As a decimal)");
if(result1 != null)
interest = Double.parseDouble(result1);
totalSave = saveAmount;
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
return total;
}
return total;
}
}
You have a return statement inside your for loop. So, the first iteration returns, exiting the for loop right away.
You have a return statement already in the correct location, after the for loop, so all you have to do is remove the return statement that is inside the for loop.
Change you loop to :
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
}
Remove the return. As soon as you do a return it stops execution of that function and return to the callers.
for(year = 1; year <= Max_Year; ++ year)
{
totalInterest = saveAmount + saveAmount * interest;
JOptionPane.showMessageDialog(null, " If you save " + moneyFormat.format(totalSave) + " each year for " + Max_Year + " years" + "\n With " + percentFormat.format(interest) + " Interest" + " Without Interest" + "\n\nAfter year " + year + " " + moneyFormat.format(totalSave) + " " + moneyFormat.format(totalInterest));
return total; //<-- PROBLEM
}
The problem is the return inside the loop. It executes one iteration and when it gets to the return statement it exits the loop. I guess you want to move it outside the loop.
Update after your comment: Try this
String resultString = "";
for(year = 1; year <= Max_Year; year++)
{
totalInterest = saveAmount + saveAmount * interest;
resultString += " If you save " + moneyFormat.format(totalSave) +
" each year for " + Max_Year + " years" + "\n" +
" With " + percentFormat.format(interest) + " Interest" +
" Without Interest" + "\n\nAfter year " + year + " " +
moneyFormat.format(totalSave) +
" " + moneyFormat.format(totalInterest) + "\n";
}
JOptionPane.showMessageDialog(null, resultString);
return total;
}
Note that this will display things the way you want to but i think your calculations go wrong somewhere.

Categories