Print statement [duplicate] - java

This question already has answers here:
How do I concatenate two strings in Java?
(23 answers)
Closed 8 months ago.
New to Java.
Does anyone know how I can print the following output:
The sum of the digits is 3 + 0 + 4 + 5 + 8 = 20
This is my print line:
System.out.print("The sum of the digits is: " + num1 + num2 + num3 + num4 + num5 + sum);
I want to get the + sign to display, but for some reason I get errors.
Any assistance is appreciated.

There is a difference between + and "+". The first is used to combine Strings in this case and the second is a String with the value of a plus sign.
So a simple plus in a String would look like this:
num1 + " + " + num2 + " = " + solution

Related

Adding Fractions (Java) [duplicate]

This question already has answers here:
How to convert decimal to fractions?
(10 answers)
Closed 3 years ago.
In this program, the user is asked for 4 integers that represent two fractions.
First ask for the numerator of the first and then the denominator.
Then ask for the numerator and denominator of the second.
The program should add the two fractions and print out
the result.
I can't figure out how to add the fractions together
public class AddFractions extends ConsoleProgram
{
public void run()
{
int nffraction = readInt("What is the numerator of the first fraction?: ");
int dffraction = readInt("What is the denominator of the first fraction?: ");
int nsfraction = readInt("What is the numerator of the second fraction?: ");
int dsfraction = readInt("What is the denominator of the second fraction?: ");
int sum =
System.out.print(nffraction + "/" + dffraction + " + " + nsfraction + "/" + dsfraction + "=" + sum);
}
}
This is the expected output "1/2 + 2/5 = 9/10" but i can't figure out the "= 9/10" part.
To get the sum of two franctions a/b + c/d you need to do (a*d + c*b)/b*d.
So for your example:
int numerator = (nffraction * dsfraction + nsfraction * dffraction)
int denominator = dsfraction * dsfraction
System.out.print(nffraction + "/" + dffraction + " + " +
nsfraction + "/" + dsfraction + "=" + numerator + "/" + denominator);
This wont reduce to the simplest form of the fraction though.

I'm not sure what to do with my code. fraction conversions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm not sure what to add to //Sample 3, can anyone help me out and tell me what I'm doing wrong? I'm writing to write the final part where else if the improper fraction converts to a whole integer, but i don't know how to write that
package ch2_project;
import java.util.Scanner;
public class Ch2_project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a numerator: ");
int numerator = input.nextInt();
System.out.print("Enter a denominator: ");
int denominator = input.nextInt();
if (numerator < denominator)
{
System.out.println(numerator + " / " + denominator + " is a proper fraction"); // Sample 2
}
else
{
int mix = numerator / denominator;
int remainder = numerator % denominator;
System.out.println(numerator + " / " + denominator + " is a improper fraction and it's mixed fraction is " + mix + " and " remainder + " / " + denominator);// Sample 1
}
else if ()
{
int whole = numerator / denominator
System.out.println(numerator + " / " + denominator + " is an improper fraction and it can be reduced to " + whole);//Sample 3
}
}
}
You're missing an addition operator before remainder causing the compiler to throw an error about an unexpected symbol. Your concatenation isn't working due to the error here:
System.out.println(numerator + " / " + denominator + " is a improper fraction and it's mixed fraction is " + mix + " and " remainder + " / " + denominator);// Sample 1
^
It should be changed to:
System.out.println(numerator + " / " + denominator + " is a improper fraction and it's mixed fraction is " + mix + " and " + remainder + " / " + denominator);// Sample 1
Notice the added + to remedy the problem, which was a missing symbol causing concatenation to fail.
Working example: Here
Edit
Seeing that you've edited the code, the else and else if statements are backwards. Also, the else if has no condition. To detect if fractions can be simplified to a whole number, do this:
else if(numerator%denominator == 0)
This will evaluate if numerator is divisible by denominator, yielding a whole number.

Converting Double to 2 Decimal Places [duplicate]

This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 6 years ago.
I have a code where an individual orders a certain number of coffees and coffee shots in each cup, and the program calculates the total price (purchasePrice). However, when i output the purchase price as a double, it only outputs a number with 1 decimal place. How can i change it to output with 2 decimal places.
double purchasePrice = 0;
for (counting = 0; counting < coffeeCups; counting++) {
System.out.println("Cup " + (counting + 1) + " has " + coffeeShots[counting] + " shot(s) and will cost $" + (2 + coffeeShots[counting]) + "\n");
purchasePrice+= 2 + (coffeeShots[counting]);
}
System.out.println(coffeeCups + " coffees to purchase.");
System.out.println("\nPurchase price is $" + purchasePrice + ".");
Please refer to Decimal Format
// 2 places of decimal
DecimalFormat formatter = new DecimalFormat( "#.00" );
System.out.println(formatter.format(1.23)); // 1.23
System.out.println(formatter.format(1)); // 1.00
System.out.println(formatter.format(1.234)); // 1.23

Recursive mystery method -- Can someone explain this to me? [duplicate]

This question already has answers here:
Understanding how recursive functions work
(18 answers)
Closed 7 years ago.
For the following method, when mystery(45) is called, the output is "1 0 1 1 0 : 2 5 11 22 45". I understand why "1 0 1 1 0 :" is printed out, but don't understand how "2 5 11 22 45" is printed out after the colon. Can someone explain this to me? I've tried writing it out, but I just could not figure it out.
public static void mystery (int n) {
if (n <= 1) {
System.out.print(": ");}
else {
System.out.print((n % 2) + " ");
mystery (n/2);
System.out.print(n + " ");
}
}
It's recursive, so the calling looks something like this.
System.out.print((45 % 2) + " ");
System.out.print((22 % 2) + " ");
System.out.print((11 % 2) + " ");
System.out.print((5 % 2) + " ");
System.out.print((2 % 2) + " ");
mystery (2 / 2); <-- won't recurse anymore, will just print :
System.out.print(2 + " ");
System.out.print(5 + " ");
System.out.print(11 + " ");
System.out.print(22 + " ");
System.out.print(45 + " ");

System.out.println( number1 + "score" + (number1 + number2) + number1 ) result explanation (string vs. numeric addition operator)

public class Test {
public static void main(String[] args) {
int number1 = 4;
int number2 = 5;
System.out.println( number1 + "Score:" + (number1 + number2) + number1 );
}
}
The output of the above is:
4Score: 94
Why is this? If there is no "score" in there, I understand the result from it, but this I don't know why. number1 and Score: outputs individually first, so then why is it effecting the result to be 94?
You have:
public static void main(String[] args) {
int number1 = 4;
int number2 = 5;
System.out.println( number1 + "Score:" + (number1 + number2) + number1);
}
This is outputting exactly what you told it to output, essentially:
"4" + "Score:" + "9" + "4"
The + operator when used with a string will convert the non-String operands to strings and concatenate the strings together. When + is used with all numeric operands, it is an arithmetic + and just adds the values together.
By putting (number1 + number2) in parentheses, you cause that to be evaluated first, and since both operands are integers, it behaves as an arithmetic + thats adds those two numbers together (producing 9). That result is then converted to a string and concatenated to everything else. It's essentially a shortcut for:
int number1 = 4;
int number2 = 5;
System.out.println( Integer.toString(number1) +
"Score:" +
Integer.toString(number1 + number2) +
Integer.toString(number1) );
If you remove "Score:", then all of the operands are integers, and so all of the + operators are arithmetic addition, and it just sums all the numbers -- i.e. a shortcut for:
System.out.println( Integer.toString(number1 + (number1 + number2) + number1) );
If you want more technical details of the + operator as related to strings vs. numbers, see Section 15.18 of the JLS (15.18.1 describes behavior for strings, 15.18.2 describes behavior for numeric types).
As an aside, the + operator is always left-associative no matter what types the operands are (described in 15.18.1). So the result of the following may surprise you:
System.out.println(1 + 2 + "string" + 1 + 2);
Spoiler (mouse over):
3string12
See http://ideone.com/P11aMI for some more working examples.
It's to do with operator precedence and the overloading of the + operator. If both sides are numbers, then the + operator performs addition:
number1 + number2
results in 9, which is evaluated first (as it's in brackets).
Then as the rest of it has the same precedence, it is overloaded to string concatenation, in left to right order. If one or all of the arguments to the operator are not numbers, they will all be implicitly converted into strings. We start off with:
4 + "Score:" + (4 + 5) + 4
As the brackets are evaluated first, we then get this:
4 + "Score:" + 9 + 4
Which becomes
"4Score:" + 9 + 4
Then
"4Score:9" + 4
And your final result will be
"4Score:94"
just as you got.
the subterm number1 + number2 is treated as an integer. So the sum could be calculated: 9. Using it as a string parameter results in an automatic cast to String, therefore the concatenation of strings is used: number1 + "Score:" + "9" + number1
System.out.println( number1 + "Score:" + (number1 + number2) + number1))
This prints out the following values (the one in the bracket results in an arithmetic sum :
4 + "Score:" + (4+5) + 4
which is
4Score:94
System.out.println( number1 + "Score:" + (number1 + number2) + number1));
it will be step by step as
1) System.out.println( 4 + "Score:" + 9 + 4));
2) System.out.println( "4Score:" + 9 + 4));
3) System.out.println( "4Score:9" + 4));
Then it shows output as
"4Score:94"

Categories