I am trying to replicate a list of conversions from kg to lbs and vice versa. I've found my desired code for output and functionality, but I am missing something to align my values to the right of the column.
Here is my code:
import java.text.*;
public class KilosTwoColumn {
public static void main(String[] args) {
System.out.println("Kilograms" + "\t" + "Pounds" + "\t" + " | " + "\t" + "Pounds" + "\t" + "Kilograms");
int count = 0;
while (count < 100) {
int kilos = count * 2 + 1;
int pounds2 = (count + 4) * 5;
double pounds = kilos * 2.2;
double kilos2 = pounds2 * .453;
DecimalFormat df = new DecimalFormat("#.#");
//if (count > 1 && count < 98) {
//System.out.println("...");
//break;
//}
System.out.printf("%-17d %.1f | %7d %.2f%n", kilos, pounds, pounds2, kilos2);
count++;
}
}
}
I am also trying to create a break in the list three rows in and resume the last two.
The problem is that you are not specifying a width for the float values, just the number of decimal places.....
For example, consider "%-17d %.1f ..." which will set the second value to be a float value with 1 decimal place, but no indication of how much space to occupy. By changing that to "%-17d %12.1f it will occupy 12 characters, with 1 decimal.
Try something like:
public class KilosTwoColumn {
public static void main(String[] args) {
System.out.printf("%12s %12s | %7s %12s\n", "Kilograms", "Pounds", "Pounds", "Kilograms");
int count = 0;
while (count < 100) {
int kilos = count * 2 + 1;
int pounds2 = (count + 4) * 5;
double pounds = kilos * 2.2;
double kilos2 = pounds2 * .453;
DecimalFormat df = new DecimalFormat("#.#");
//if (count > 1 && count < 98) {
//System.out.println("...");
//break;
//}
System.out.printf("%12d %12.1f | %7d %12.1f\n", kilos, pounds, pounds2, kilos2);
count++;
}
}
}
For me, the above process outputs:
Kilograms Pounds | Pounds Kilograms
1 2.2 | 20 9.1
3 6.6 | 25 11.3
....
199 437.8 | 515 233.3
Related
So I am doing a digit counter thing basically
I want it to display 123 and which number is what place value for example 123
------------------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------------------
this is my code
import java.util.Scanner;
public class digits {
public static void main(String[] args)
{
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int num1 = number % 10;
int num2 = number / 10 % 10;
int num3 = number / 100 % 10;
int num4 = number / 1000 % 10;
int num5 = number / 10000 % 10;
int num6 = number / 100000 % 10;
int num7 = number / 1000000 % 10;
int num8 = number / 10000000 % 10;
scann.close();
System.out.println("Ones: "+num1);
System.out.println("Tens: "+num2);
System.out.println("Hundreds: "+num3);
System.out.println("Thousands: "+num4);
System.out.println("Ten-Thousands: "+num5);
System.out.println("Hundred-Thousands: "+num6);
System.out.println("Millions: "+num7);
System.out.println("Ten-Millions: "+num8);
}
}
How do I stop it from printing the rest if I only type 123?
Output I got
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
Thousands: 0
Ten-Thousands: 0
Hundred-Thousands: 0
Millions: 0
Ten-Millions: 0
------------------------
Output I want
--------------------------
Enter any number: 123
Ones: 3
Tens: 2
Hundreds: 1
------------------------
You need to introduce a condition (or conditions) in your code.
You can achieve that with a chain of if statements. But the better way to do it is by utilizing a loop. Because that will allow you to get rid of the intermediate variables (num1, num2, etc) and to avoid duplicating the line of code that prints the remainder on the consol. That will make the code more readable and concise.
In order to be able to apply the loop for this problem, you need to create an array of strings that will store all quantifiers ("Ones: ", "Tens: ", etc).
It can be done like that:
public static final String[] quantifiers =
{"Ones: ", "Tens: ", "Hundreds: ", "Thousands: ",
"Ten-Thousands: ", "Hundred-Thousands: ", "Millions: ", "Ten-Millions: "};
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
int number = scann.nextInt();
for (int i = 0; i < quantifiers.length && number > 0; i++) {
System.out.println(quantifiers[i] + number % 10);
number /= 10; // does the same as number = number / 10;
}
}
output for input 123
Ones: 3
Tens: 2
Hundreds: 1
It might help your question. Because of hardcoded terms such as 'tens' or 'hundreds', it is not generic enough.
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scann.nextInt();
int length = String.valueOf(number).length();
for(int i=0; i< length; i++){
if(i == 0){
System.out.println("Ones: "+ number % 10);
}else if(i == 1)
System.out.println("Tens: " + number / 10 % 10);
else if(i == 2)
System.out.println("Hundreds: "+ number / 100 % 10);
else if(i == 3)
System.out.println("Thousands: "+ number / 1000 % 10);
else if(i == 4)
System.out.println("Ten-Thousands: "+ number / 10000 % 10);
else if(i == 5)
System.out.println("Hundred-Thousands: "+ number / 100000 % 10);
else if(i == 6)
System.out.println("Millions: "+ number / 1000000 % 10);
else if(i == 7)
System.out.println("Ten-Millions: " + number / 10000000 % 10);
}
scann.close();
}
Your code is printing all the numbers because that's what you wrote:
System.out.println("Ones: "+num1);
...and so on.
If you never want to print e.g. thousands, just remove the println for thousands. If you only want to print them if someone actually enters thousands, add an if statement:
if (num4 > 0) {
System.out.println("Thousands: "+num4);
}
Repeat for the others.
Let's say I have a number from user, for exemple: 456789.
I know how to print in reverse the number, but I am not sure how I can stop the execution to print only 3 first reversed digits.
What I mean is that I want to print only 987 from the given number
I have to stop somehow with break; but I am not sure how.
public static void main(String[] args) {
int number= 0;
int numberInReverse = 0;
System.out.println("Input a number");
Scanner sc=new Scanner(System.in);
numar=sc.nextInt();
while (number !=0){
numberInReverse*=10;
numberInReverse=numar%10;
number/=10;
System.out.print(numberInReverse);
}
}
You could follow this algo:
modulo the number by 1000
reverse it
print
You can just convert to into a StringBuilder and use reverse() and substring():
String result = new StringBuilder()
.append(numar)
.reverse()
.substring(0, 3);
System.out.print(result);
System.out.println("Input a number");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int reversed = 0, counter = 0;
while (counter++ < 3) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
For the example of num = 456789
We have:
a) A quotient of 45678 when we do an Integer division, i.e. 456789 / 10
b) A remainder of 9 when we use the Modulus operator, i.e. 456789 % 10
If we update the 'new' number to be the quotient and by iterating,
the following table shows what it looks like:
digit number quo rem Observations
----- ------ ----- --- --------------------------------------------
1 456789 45678 9
2 45678 4567 8
3 4567 456 7 STOP for 3 digits, i.e. number of iterations
4 456 45 6
5 45 4 5
6 4 0 4 BREAK when variable 'quo' equals ZERO
For a first approach, consider calling the following method from your main():
static void firstApproach(){
int num= 456789;
int quo= num / 10;
int rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
}
This is the output we get:
456789 | 45678 | 9
Now, consider a second iteration by calling this method from main():
static void secondIteration() {
int num= 456789;
int quo= num / 10;
int rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
num= quo;
quo= num / 10;
rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
}
Here's the output for two iterations:
456789 | 45678 | 9
45678 | 4567 | 8
Carry on for yet a third iteration:
static void thirdIteration() {
int num= 456789;
int quo= num / 10;
int rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
num= quo;
quo= num / 10;
rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
num= quo;
quo= num / 10;
rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
// ... and so on ...
}
And the output, after 3 iterations:
456789 | 45678 | 9
45678 | 4567 | 8
4567 | 456 | 7
Looking at the code for third iteration, observe the following repeating pattern that should go inside the body of a loop:
num= quo;
quo= num / 10;
rem= num % 10;
What if we try to specify some unreasonable amount of digits, say 10 for the same example of 456789?
This is why the loop needs two stoping conditions (whichever occurs first), namely:
- when it reaches the specified number of digits (3 in the example);
- when quotient gets to ZERO (hence the break;).
The following reverse() method shows a while() loop, where all variables are properly initialised to avoid any surprises. Tha variable digit is the one that controls the number of iterations for the loop and is incremented at the end:
static int reverse( int number, int numDigits ){
int res= 0;
int quo= number / 10;
int rem= number % 10;
int digit= 1;
while( (digit <= numDigits) && (quo != 0) ){
res= 10*res + rem;
number= quo;
quo= number / 10;
rem= number % 10;
digit= digit + 1;
}
return res;
}
The above reverse() method can be called from main():
public static void main( String args[] ){
// firstApproach();
// secondIteration();
// thirdIteration();
int result= reverse( 456789, 3 ); // reverses 456789, upto 3 digits
System.out.println( result );
}
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
}
I have a homework assignment where I have to covert any base to base 10. I have some given numbers, which are the "basen". I have to convert those bases to base 10. The only part that I am stuck in is this part of the code:
answer = ; // Not sure what I have to put in here
I have seen some other posts about converting to base ten, but I am just not sure how to how to incorporate them into my code.
public class BaseN {
public static final int BASEN_ERRNO = -1;
public static int digit = 0;
public static void main(String[] argv) {
basen(512, 6);
basen(314, 8);
basen(49, 5);
basen(10101, 2);
}
public static void basen(int n, int b) {
int ans = basen(n, b, 1, 0);
if (ans == BASEN_ERRNO)
System.out.println(n + " is not a valid base-" + b + " number");
else
System.out.println(n + " base-" + b + " = " + ans + " base-10");
}
public static int basen(int number, int base, int placevalue, int answer) {
if (number == 0) return answer;
digit = number % 10;
if (digit >= base) return BASEN_ERRNO;
answer = 1;// not sure what to put here
number = 0;
placevalue = 0;
return basen(number, base, placevalue, answer);
}
}
You could look at a k length number of base n like this:
x(0)*n^(k-1) + x(1)*n^(k-2) + ... + x(k-1)*n^1 + x(k)*n^0
Where x(0), x(1), ..., x(k) is the digit at position k from the left.
So, if you are trying to convert, say, 101 base 2 to base 10 you would do the following :
1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5 base 10
say you want to convert the number 352 from base 6:
3 * 6^2 + 5 * 6^1 + 2 * 6^0 = 108 + 30 + 2 = 145 base 10
What you're looking for code wise is something like this :
int[] digits = {3, 5, 2};
int base = 6;
int answer = 0;
for(int i = digits.length - 1; i >= 0; i--)
{
answer += digits[i] * Math.pow(base,digits.length-i-1);
}
return answer;
which will return 145.
Hopefully even though my implementation is iterative you should be able to apply it to your recursive implementation as well.
You can implement the following algorithm. Lets say you are given String number which represents the number you want to convert to decimal form and int base which represents the base of given number. You can implement function int convertToNumber(char c); which accepts one character representing one digit from your number and will map characters to numbers like this:
0 -> 0,
1 -> 1,
... ,
A-> 10,
B -> 11,
... ,
F -> 15,
...
Then you just iterate through your given string and multiply this functions output with base to the power of iteration. For example, convert number A32(hexadecimal):
A32 = convertToNumber(A) * b ^ 2 + convertToNumber(3) * b ^ 1 + convertToNumber(2) * b ^ 0 = 10 * 16 ^ 2 + 3 * 16 ^ 1 + 2 * 16 ^ 0 = 10 * 16 * 16 + 3 * 16 + 2 = 2610 (decimal).
public class BaseConvert {
public static int convertDigitToNumber(char c) throws Exception {
if(c >= '0' && c <= '9') return c - '0';
if(c >= 'A' && c <= 'Z') return c - 55;
if(c >= 'a' && c <= 'z') return c - 97;
throw new Exception("Invalid digit!");
}
public static int convertToBase(String number, int base) throws Exception {
int result = 0;
for(int i = 0; i < number.length(); i++){
result += convertDigitToNumber(number.charAt(i)) * (int)Math.pow(base, number.length() - i - 1);
}
return result;
}
public static void main(String[] args) {
try{
System.out.println(convertToBase("732", 8));
System.out.println(convertToBase("A32", 16));
System.out.println(convertToBase("1010", 2));
}catch (Exception e) {
System.out.print(e);
}
}
}
Is there a way I can compare (>, <, >=, <=, !=, ==) a decimal represented as a long and int?
If the number is 3214.21 then it would be represented in a class like this
long units = 321421;
int precision = 2;
// to get the original number I would do units * 10^precision
I would like to be able to do something similar to BigDecimal's compareTo() method. So greater than returns 1, equals returns 0, less than returns -1.
What I am currently doing does not work for some cases. The code that causes it to function that way is outlined below. The method is more or less a proof of concept.
public int compareTo(Money other) {
if (precision == other.getPrecision()) { // fast check if precision is the same
if (units > other.getUnits()) return 1; // we forgot to inverse/flip here. will be an issue for non-decimal
else if (units < other.getUnits()) return -1;
else return 0; // least likely
}
int intX = (int) (units / (Math.pow(10, precision))); // converted units whole numbers to int
int fractionX = (int) (units % (Math.pow(10, precision))); // converts the decimal as an int
int intY = (int) (other.getUnits() / (Math.pow(10, other.getPrecision()))); // converted units whole numbers to int
int fractionY = (int) (other.getUnits() % (Math.pow(10, other.getPrecision()))); // converts the decimal as an int
System.out.println("Test: i " + intX + "| f " + fractionX + "| u " + units + "| p " + precision);
System.out.println("Test2: i " + intY + "| f " + fractionY + "| u " + other.getUnits() + "| p" + other
.getPrecision
());
if (intX > intY) return 1;
else if (intX < intY) return -1;
else {
if (fractionX > fractionY) return 1; // this is where the logic fails
if (fractionX < fractionY) return -1;
else return 0;
}
}
Here is my test along with output
System.out.println(MoneyFactory.fromString("0.3").compareTo(MoneyFactory.fromString("0.29")));
System.out.println(MoneyFactory.fromString("13").compareTo(MoneyFactory.fromString("0.31456789")));
System.out.println(MoneyFactory.fromString("0.2999").compareTo(MoneyFactory.fromString
("0.3")));
Output
Test: i 0| f 3| u 3| p 1
Test2: i 0| f 29| u 29| p2
-1
Test: i 13| f 0| u 13| p 0
Test2: i 0| f 31456789| u 31456789| p8
1
Test: i 0| f 2999| u 2999| p 4
Test2: i 0| f 3| u 3| p1
1
The simplest solution would be to convert one number to the common precision level and then compare the numbers. If they are the same use `number with bigger precision' logic (in pseudo code):
return (number1 == number2) ? [number with bigger precision logic] : number1 - number2
In Java code
class Money {
long units;
int precision;
public Money (long un, int prec) {
units = un;
precision = prec;
}
public int compareTo(Money other) {
int preResult = this.precision - other.precision;
long first = (preResult > 0) ? ((long)(this.units / Math.pow(10, preResult))) : this.units;
long second = (preResult < 0) ? ((long)(other.units * Math.pow(10, preResult))) : other.units;
return (first == second) ? preResult : Long.compare(first, second);
}
public static void test() {
Money first = new Money(2345L, 4);
Money second = new Money(234567L, 6);
System.out.println(first.compareTo(second));
}
}
EDIT: There was an error in the code. Changing the 1 in both tenary checks to 0 fixes this issue
I think you just do it like this:
public int compareTo(Money other) {
return Double.compare(units/Math.pow(10, precision), other.getUnits()/Math.pow(10, other.getPrecision()));
}