why does it print twice? if -else [duplicate] - java

This question already has answers here:
Java - Looping 2d Array to find index of a value not working
(2 answers)
Closed 7 years ago.
I'm learning java atm , and had to write a code to calculate the monetary units, and only display the nonzero denominations using singular words for single units and plural words for plural units.
This is the code so far:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
// receive amount
System.out.println("Enter an amount in double, for example 11.56: ");
double amount = input.nextDouble();
int remainingAmount = (int)(amount * 100);
// find the number of one dollars
int numberOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// find the number of quarters in the remaing amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
//find the number of dimes in the remaing amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
//find the number of nickels in the remaing amount
int numberOfNickles = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
//find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
//Display results
System.out.println("Your amount" + amount + "consists of");
if (numberOfDollars > 1) {
System.out.println(" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1); {
System.out.println(" " + numberOfDollars + "dollar");
}
The output is:
run:
Enter an amount in double, for example 11.56:
12,33
Your amount12.33consists of
12dollars
12dollar
1quarters
1quarter
0dimes
0dime
1nickles
1nickle
3pennies
3penny
Why is everything printed double? 3 == not 1 so why does it still say 3 penny?
Noob question maybe, but thats because i am one :) Thanks for help!

Because you added a random ; after the second if. Therefor your second System.out.println is not part of the if-statement. Remove it:
if (numberOfDollars > 1) {
System.out.println (" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1) {
System.out.println (" " + numberOfDollars + "dollar");
}

Remove the semicolon after if();
if (numberOfDollars == 1);
The second print statement is printing because it is not a part of if(); due to the semicolon that you have after if()

replace
else if (numberOfDollars == 1); { // with ;, condition terminates here itself
with
else if (numberOfDollars == 1) {
Semicolon at the end of If statememnt , finish the statement in single line. Means it ignores the result of condition and continue the execution from the next line.

Related

converting from if-else to methods

Here is my current code:
import java.util.Scanner;//importing scanner
public class QuestionOne {
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
//above three lines ask for number of days until a value that fits within specification is obtained
}
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
//above two lines print day and share points, as well as the first line of text (as it does not change)
for (int i = 2; i <= numberofDays; i++) {
if (numberofDays % 2 == 0)
if (i <= numberofDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
} else {
if (i <= numberofDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
// above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
}
This code compiles and works as I want, however, I no longer want it to be in this format. Instead, I would like for it to contain a method named DisplayStock; the input arguments I want for this method are the
number of days in the period and the share points on the first day. The method is used to increase the share points by 50 and decrease the share points by 25 on alternate days in the specified period. The method then
displays a table showing the days and the share points on those days. This method doesn’t return anything.
As for the main method, it will first ask the users to enter the number of days in the specified period and the share points on the first day (with input validation, the program should then call the DisplayStock method that outputs the table.
A sample output currently looks as such if the period is ll days and SharePoint are 550:
Day Share Points
1 550
2 600
3 575
4 625
5 600
6 650
7 625
8 675
9 650
10 700
11 675
So basically, what I am intending to do is convert the code from if-else statements over to methods to alleviate issues with readability and function. Any help would be appreciated! I will continue to work on this but I do not think I will be able to get as far as I intend.
you just want to break the code in to two methods or several
basic will be this:
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
numberofDays = validator(numberofDays,keyboard); // Validates Keyboard input
//above two lines print day and share points, as well as the first line of text (as it does not change)
outPutTablePrinter(numberofDays,sharePoints);
}
private static void outPutTablePrinter(int numberOfDays,int sharePoints){
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
for (int i = 2; i <= numberOfDays; i++) {
if (numberOfDays % 2 == 0)
if (i <= numberOfDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
} else {
if (i <= numberOfDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
// above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
private static int validator(int numberOfDays,Scanner keyboard){
while (numberOfDays < 10 || numberOfDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberOfDays = keyboard.nextInt();
}
return numberOfDays;
}
I refactored your code. First, I would prefer printf and your logic can be greatly simplified by incrementing by two in your loop. You do need to check if there is an index + 1 for it to work correctly with odd number of days, but you can do
System.out.printf("Day\tShare Points%n");
for (int i = 0; i < numberofDays; i += 2) {
System.out.printf("%-3d\t%d%n", i + 1, sharePoints);
sharePoints += 50;
if (i + 1 < numberofDays) {
System.out.printf("%-3d\t%d%n", i + 2, sharePoints);
sharePoints -= 25;
}
}
And I get
Day Share Points
1 550
2 600
3 575
4 625
5 600
6 650
7 625
8 675
9 650
10 700
11 675
Following code be used:
import java.util.Scanner;//importing scanner
public class QuestionOne{
static int numberofDays;//these two lines define variables
static int sharePoints;
public static void main(String[]args){
Scanner keyboard = new Scanner (System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
//above three lines ask for number of days until a value that fits within specification is obtained
}
DisplayStock ();
}
public static void DisplayStock (){
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
//above two lines print day and share points, as well as the first line of text (as it does not change)
for(int i = 2; i <= numberofDays; i++)
{
if(numberofDays % 2 == 0)
if(i <= numberofDays/2)
{
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
}
else
{
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
else
{
if(i <= numberofDays/2 + 1)
{
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
}
else
{
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
//above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
}

my guessing game counter keeps rising

so for class I'm supposed to make a guessing game that gives you clues as you get closer to the answer. My question is when i run it and i get one Number correct, I would obviously keep that number and keep going with the other 4 numbers, when I do that, the problem is my correct digits counter keeps rising even if I don't get other digits correct.. how would I remedy this? Would i be able to add breaks in each of the if statements or would that completely exit me out of my do while loop?
public class GuessingGame {
public static void main(String[] args) {
int guess,numDigitsCorrect=0,sumDigitsCorrect=0,attempts=0,answer;
Random rng = new Random();
Scanner consoleScanner = new Scanner(System.in);
answer = rng.nextInt(90000) + 10000;
System.out.println("I have randomly chosen a 5-digit code for you to guess.Each time you guess,\n"
+ "I will tell you how many digits are correct and the sum of the digits that are correct."
+ "For example, if the number is \"68420\" and you guess 12468, I will respond:\n"
+ "Number of Digits Correct: 1\n"
+ "Sum of Digits Correct: 4\n"
+ "From deduction, you will know the 4 was correct in the guess."
+ "\nNow its your turn..................................................................");
do{
System.out.print("Please enter a 5-digit code (your guess): ");
guess = consoleScanner.nextInt();
int g1 = guess/10000;
int g2 = guess%10000/1000;
int g3 = guess % 10000 % 1000 / 100;
int g4 = guess % 10000 % 100 /10;
int g5 = guess % 10000 % 10 / 1;
int a1 = answer/10000;
int a2 = answer%10000/1000;
int a3 = answer % 10000 % 1000 / 100;
int a4 = answer % 10000 / 100 / 10;
int a5 = answer % 10000 % 10 / 10;
if(g1 == a1)
{
numDigitsCorrect ++;
sumDigitsCorrect += a1;
System.out.println("\nNumber of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if(g2 == a2)
{
numDigitsCorrect ++;
sumDigitsCorrect += a2;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g3 == a3)
{
numDigitsCorrect ++;
sumDigitsCorrect += a3;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g4 == a4)
{
numDigitsCorrect ++;
sumDigitsCorrect += a4;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if (g5 == a5)
{
numDigitsCorrect ++;
sumDigitsCorrect += a5;
System.out.println("Number of digits correct: " + numDigitsCorrect) ;
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
System.out.println();
}
if(guess == answer)
{
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
}while (guess != answer);
}
}
Few things to fix -
Make sure your a4, a5 are correct
int a4 = answer % 10000 % 100 / 10; // note the modulus
int a5 = answer % 10000 % 10; // note divided by 1 or remove the redundant statement
Move your print statement out of your if block to the end of all if inside the do block as -
if (g1 == a1) {
numDigitsCorrect++;
sumDigitsCorrect += a1;
}
... //other if statements
if (guess == answer) {
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
System.out.println("Number of digits correct: " + numDigitsCorrect);
System.out.println("Sum of digits correct: " + sumDigitsCorrect);
Also since you already do a check
if (guess == answer) {
System.out.println("****HOORAY! You solved it. You are so smart****");
break;
}
within your do you can change your while condition to true as -
do {
... your existing code
} while(true);
To answer
Would i be able to add breaks in each of the if statements
If you do so, for even a single digit match your loop will exit(break).
Importantly to fix the counter, initialize the counter within the do block as
do {
numDigitsCorrect = 0;
sumDigitsCorrect = 0;
.. // existing logic
}

reversing digits numbers in java [duplicate]

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 8 years ago.
I've looked around and came up with this solution, but it doesn't seem to be working. Does anyone have an idea? I need to get a number from the user that is only 3 digits and positive. after that, to reverse the 3 digits. what i wrote below only give me the last digit out of the three that I need.
int reversedNum=0;
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a 3 digit positive number whose first and last digits are different: ");
int userNumber = scan.nextInt();
if (userNumber >= 100 && userNumber <= 999)
{
System.out.println("User number is: " + userNumber);
reversedNum = (reversedNum*10) + (userNumber%10);
userNumber = userNumber/10;
System.out.println("Difference "+reversedNum);
}
else
System.out.println("The number you entered is not a 3 digit positive number");
When you do
reversedNum = (reversedNum*10) + (userNumber%10);
userNumber = userNumber/10;
reversedNum is 0 so you end up with only userNumber%10.
You need something like this:
int hundreds = (int)(userNumber/100);
int remaining = userNumber-100*hundreds;
int dec = (int)(remaining /10);
remaining -= 10*dec;
int reversed = 100*remaining + 10*dec + hundreds
System.out.println("Reversed: " + reversed);
System.out.println("Difference " + (userNumber-reversed);
You can use % operator in order to print the last digit of input and then use / between int operand to get remaining digits
while(input%10 != input) {
int mod = input % 10;
System.out.print(mod);
input /= 10;
}
String result = "" + Integer.toString(userNumber).charAt(2) + Integer.toString(userNumber).charAt(1) + Integer.toString(userNumber).charAt(0);
int reversedNum = Integer.valueOf(result);
That will reverse your integer.
To reverse the number the logic should be as below. Use % and / operator to find the individual digit.
if (userNumber >= 100 && userNumber <= 999)
{
System.out.println("User number is: " + userNumber);
int unitdigit = userNumber%10;
userNumber = userNumber/10;
int tenthdigit = userNumber%10;
int lastdigit = userNumber/10;
reversedNum = (unitdigit*100) + (tenthdigit*10) + lastdigit;
System.out.println("reversed numnber "+reversedNum);
}

Change Machine Math & Logic Errors

I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?

Java while loops/ math logic

I'm new to Java and also new to while, for, and if/else statements. I've really been struggling with this beast of a problem.
The code and description is below. It compiles, but I'm it doesn't calculate as expected. I'm not really sure if it's a mathematical logic error, loop layout error, or both.
I've been grinding my gears for quite some time now, and I'm not able to see it. I feel like I'm really close... but still so far away.
Code:
/*
This program uses a while loop to to request two numbers and output (inclusively) the odd numbers between them,
the sum of the even numbers between them, the numbers and their squares between 1 & 10, the sum of the squares
of odd numbers.
*/
import java.io.*;
import java.util.*;
public class SumOfaSquare
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int firstnum = 0, secondnum = 0, tempnum = 0;
int sum = 0,squaresum = 0, squarenum = 0;
int number = 1;
String oddOutputMessage = "The odd numbers between" + firstnum + " and " + secondnum + " inclusively are:";
String evenSumMessage = "The sum of all even numbers between " + firstnum + " and " + secondnum + "is: ";
String oddSquareMessage = "The odd numbers and their squares are : ";
String squareMessage = "The numbers and their squares from 1-10 are : ";
System.out.println ("Please enter 2 integers. The first number should be greater than the second: ");
firstnum = console.nextInt();
secondnum = console.nextInt();
//used to find out if first number is greater than the second. If not, inform user of error.
if (firstnum > secondnum)
{
tempnum = firstnum;
System.out.println ("You entered: " + firstnum + " and: " + secondnum);
}
else
System.out.println ("Your first number was not greater than your second number. Please try again.");
//while the frist number is greater, do this....
while (tempnum <= secondnum)
{
//if it's odd....
if (tempnum %2 == 1)
{
oddOutputMessage = (oddOutputMessage + tempnum + " ");
squaresum = (squaresum + tempnum * tempnum);
}
//otherwise it's even..
else
{
sum = sum + tempnum;
evenSumMessage = (evenSumMessage + sum + " ");
tempnum++;
}
}
// figures squares from 1 - 10
while (number <=10)
{
squarenum = (squarenum + number * number);
squareMessage = (squareMessage + number + " " + squarenum);
number++;
}
oddSquareMessage = oddSquareMessage + squaresum;
System.out.println (oddOutputMessage);
System.out.println (oddOutputMessage);
System.out.println (squareMessage);
System.out.println (evenSumMessage);
System.out.println (oddSquareMessage);
}
}
In your first loop, think hard about the conditions under which you increment tempnum. What happens when it's odd? Does tempnum get incremented?
There are a number of problems with your code. I'd rather you work through the problem yourself. You can use "println" debugging to print out the variables along the way if you don't know how to debug code.
Take the input 3 and 1 and walk through your program line by line and think about what the answer is going to be in your head (or on paper). See if that matches your expected results.
Here are some general comments about your code:
Consider breaking the different output into different subroutines: dumpOddNumbers(low, high), sumEvenNumbers(low, high), ...
Try to limit a variables scope as much as possible. Don't define the variables at the top and then use them later. Try to define them right before you need them. This will limit your unintended consequences. Try to not re-use variables unless it is temporary counters.
while (tempnum <= secondnum) These sort of lines should be for loops. One of the problems with the code is that if the first number is < then the second (the input 1 10 for example), the program loops forever because tempnum is not incremented if the number is odd.
while (tempnum <= secondnum) should probably be for (int tempnum = firstnum; tempnum <= secondnum; tempnum++)
while (number <= 10) should be for (int number = 1; number <= 10; number++)
You define the message at the top of your program but you shouldn't tack on results later. Do something like println(msgString + resultValue).
Take a look at StringBuilder() instead of msg = msg + ... type of logic. Much more efficient.
When you check the numbers are in the right order and spit out an error message, are you sure you want to continue? I think you should return there.
The following code does not match the comment. Which is correct?
// while the frist number is greater, do this
while (tempnum <= secondnum) {
Hope this helps.

Categories

Resources