This question already has answers here:
Format Float to n decimal places
(11 answers)
Closed 9 years ago.
I have the following code and my output is working but I don't know how to use the printf to make this output (66.67%) instead of 66.66666666666667%, just for an example. Any help is appreciated!
public static void evenNumbers(Scanner input)
{
int numNums = 0;
int numEvens = 0;
int sum = 0;
while (input.hasNextInt())
{
int number = input.nextInt();
numNums++;
sum += number;
if (number % 2 == 0)
{
numEvens++;
}
}
System.out.println(numNums + " numbers, sum = " + sum);
System.out.println(numEvens + " evens " + (100.0* numEvens / numNums + "%"));
}
Thank you
You can use the printf modifier %.2f to get only two decimal places.
Use String.format and %.2f:
String.format("%d evens %.2f%%", numEvens, 100.0 * numEvens / numNums);
You can use Math.round on the answer before you print it:
System.out.println(numEvens + " evens " + Math.round((100.0* numEvens / numNums)*100)/100.0d + "%"));
Don't use printf here. Instead, use MessageFormat or DecimalFormat.getPercentInstance().
String format = "{numbers: {0, number, integer}," +
" sum: {1, number, integer}\n" +
"evens: {2, number, integer}," +
" {3, number, percent}"
String message = MessageFormat.format(format,
new Object[]{numNums, sum, numEvens, ((double) numEvens)/ numNums)});
System.out.println(message);
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
My programming course wants me to have this kind of endcome:
Enter the first number!
9
Enter the Second number!
5
9 + 5 = 14
9 - 5 = 4
9 * 5 = 45
9 / 5 = 1.8 and this is the problem, the program I've written only gives me 1.0 as an answer. How can I get this number to be 1.8 not 1.0?
public class Nelilaskin {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number!");
int first = Integer.valueOf(reader.nextLine());
System.out.println("Enter the second number!");
int second = Integer.valueOf(reader.nextLine());
int plus = (first + second);
int minus = (first - second);
int multi = (first * second);
double division = (first / second * 1.0);
System.out.println(first + " + " + second + " = " + plus);
System.out.println(first + " - " + second + " = " + minus);
System.out.println(first + " * " + second + " = " + multi);
System.out.println(first + " / " + second + " = " + division);
}
}
Consider replacing the data type for first and second as Float.
And store the resultant in a float variable as well, then the output would be as required.
float plus = (first + second);
float minus = (first - second);
float multi = (first * second);
float division = first / second;
this is because you are dividing two int values, try to cast at least one of them to double..
double division = (double)first / (double)second ;
This question already has answers here:
How to concatenate int values in java?
(22 answers)
Closed 3 years ago.
I am writing some code that gives me a random string of numbers, they need to list under on integer but each number needs to be under a different math.random. For Instance, if two separate number are listed like 5 and 7, I don't want it to print 12, I would like it to print 57. But i don't want to use the System.out.println(Number1+Number2); way.
I have tried using the "&" Sign multiple ways but none seem to work.
int Number1 = 1 + (int)(Math.random() * ((5) + 1));
int Number2 = 1 + (int)(Math.random() * ((5) + 1));
int Number3 = 1 + (int)(Math.random() * ((5) + 1));
int finalcode=Number1&Number2&Number3;
System.out.println("Promo Code Genorator:");
System.out.println(" ");
System.out.println("Your Promo Code Is: "+finalcode);
Instead, what happens is it picks the lowest number from there and prints them. Any Ideas?
It is suggested to use String if you want to combine a variety of numbers together.
You can write it like this:
int Number1 = 1 + (int)(Math.random() * ((5) + 1));
int Number2 = 1 + (int)(Math.random() * ((5) + 1));
int Number3 = 1 + (int)(Math.random() * ((5) + 1));
String finalcode = String.valueOf(Number1) + String.valueOf(Number2) + String.valueOf(Number3);
System.out.println("Promo Code Genorator:");
System.out.println(" ");
System.out.println("Your Promo Code Is: "+finalcode);
If you really need your final code to be a integer, you can use
int finalcode = Integer.parseInt(String.valueOf(Number1) + String.valueOf(Number2) + String.valueOf(Number3));
in which Integer.parseInt(String string) takes in a string and return a integer.
FYI, if you want to convert it to long instead of integer, use Long.parseLong(String string).
Hope this helps!
This seems like a nice problem to solve using streams and functional programming.
import java.util.stream.Stream;
import java.util.stream.Collectors;
public class LazyNumbersTest {
public static void main(String[] args) {
int result = Integer.parseInt(
Stream.generate(() -> (int)(Math.random() * ((5) + 1)))
.peek(System.out::println)
.limit(3)
.map(Object::toString)
.collect(Collectors.joining(""))
);
System.out.println("Promo Code Generator:");
System.out.println(" ");
System.out.println("Your Promo Code Is: " + result);
}
}
It's an infinite stream of random numbers, from which we pluck the first 3 and convert them to string, then join them together and convert to an integer.
If you want more or less numbers in the calculation, just change the number in limit. It's a shame I couldn't include the parseInt in the stream of fluent operations (without making it really ugly).
I need to build a loop that does this: 3 = Math.log10( result of number squared )/Math.log10( number inputed ) number_to_be_cubed
double cubed;
double answer;
answer = 1;
cubed = 0;
while (cubed <= 3) {
cubed = (double) Math.log( answer )/Math.log( number_to_be_cubed );
answer ++;
}
double answer_for_cubed = answer;
System.out.println("answer_for_cubed " + answer_for_cubed);
Based on the fact that A^3=B and 3=logB/logA are the same thing. Instead, I know I could use math.pow but I'm trying to solve x^3 with logs. I think it's not working because of the way java handles numbers. Is this possible? Am I looping the wrong way? I have been looking everywhere on the internet and i haven't found a problem like this.
this worked
public static void main(String[] args) {
Double cubed = 0d;
Double answer = 0d;
while (cubed.compareTo(3d) <0) {
answer ++;
cubed = Math.log( answer )/Math.log( 4 );
System.out.println(cubed + " " + answer);
}
double answer_for_cubed = answer;
System.out.println("answer_for_cubed " + answer_for_cubed);
}
result is:
answer_for_cubed 64.0
How do I set a maximum length for a double?
double divSum = number1 / number2;
String divDisplay = number1 + " / " + number2 + " = " + divSum + " ";
JLabel divSumLabel= new JLabel();
divSumLabel.setText(divDisplay)
How do I set the maximum lenght for divSum?
1 / 3 = 0.333333... How do I set the maximum lenght, so its only 0.333?
I could do:
int maxLenght = 3;
String stringDivSum = String.valueOf(divSum);
String shortDivSum = null;
if(stringDivSum.length() > maxLenght){
shortDivSum = stringDivSum.substring(0, maxLenght);
}
String divDisplay = number1 + " / " + number2 + " = " + shortDivSum + " ";
But when I then do 1 / 3 it prints out 1 / 3 = 0.3?
Use String.format(...)
String.format()
double divSum = Double.parseDouble(String.format("%.3f",(double)number1 / number2)) ;
Precision, double.
We can specify the precision of a double or float. We use the "f" to
indicate a floating-point. Before this we specify ".3" to mean "three
numbers after the decimal."
double dblValue2 = Math.round( .333333 * 1000.0 ) / 1000.0;
this will help you
String.format("%.2f", (double)value);
You can try
System.out.format("%.2f + %.2f = %.2f",number1,number2,divsum)
You basically tell the formatter to expect 3 floats with 2 decimals with %.2f. It is important to supply the variables in order you want them to, so writing ,number1,number2,divsum will yield different results than writing ,number2,number1,divsum If you want to print int, short or long, you use %d. If you want to print string you use %s. But you can also google that.
Also, storing numeric data in String in case of mathematical operations is kind of pointless exercise and only bloats your code.
If you want to store the result of the division with a scale of 3 (i.e. 3 digits after the decimal point), you need to use a BigDecimal for this. This class allows to do arbitrary-precision calculus on decimal values.
int number1 = 1, number2 = 3;
BigDecimal divSum = BigDecimal.valueOf(number1).divide(BigDecimal.valueOf(number2), 3, RoundingMode.DOWN);
The divide(divisor, scale, roundingMode) function of BigDecimal can take a scale (here set to 3) and a rounding mode (here set to DOWN, this rounding mode truncates after the scale has been reached, which is what we want here). This will perform the division and the result will be rounded down with a scale of 3.
You can then print the result with:
String divDisplay = number1 + " / " + number2 + " = " + divSum + " ";
System.out.println(divDisplay); // prints "1 / 3 = 0.333"
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);
}