How to align numbers in Java - java

So i'd like to align the row that displays the tenth year with rest of the numbers.
I've tried printf but it doesn't seem to work.
I've looked at many posts already but everything seems to be roaming around printf with some string formats.
If you can juste explain how to do it to me with some examples it would help me a lot.
Thanks for the help.
public class Foo {
public static void main(String[] args) {
double capitalDeDepart = capitalDepart(0);
double tauxInteretAnnuel = interetAnnuel(0);
double anneeTotalPlacement = dureePlacement(0);
affichage();
calcul(capitalDeDepart, tauxInteretAnnuel, anneeTotalPlacement);
}
public static double capitalDepart(double capitalDeDepart) {
Scanner clavier = new Scanner(System.in);
System.out.print("Indiquez le capital de départ : ");
capitalDeDepart = clavier.nextDouble();
return capitalDeDepart;
}
public static double interetAnnuel(double tauxInteretAnnuel) {
Scanner clavier = new Scanner(System.in);
System.out.print("Inscrivez le taux d'intérêt annuel : ");
tauxInteretAnnuel = clavier.nextDouble();
return tauxInteretAnnuel;
}
public static double dureePlacement(double anneeTotalPlacement) {
Scanner clavier = new Scanner(System.in);
System.out.print("Indiquez la durée du placement en années : ");
anneeTotalPlacement = clavier.nextDouble();
return anneeTotalPlacement;
}
public static void affichage() {
System.out.println("Année Capital Intérêt Nouveau capital");
System.out.println("----------------------------------------------");
}
public static void calcul(double capitalDeDepart, double tauxInteretAnnuel, double anneeTotalPlacement) {
int annee = 0;
double interet = 0;
double nouveauCapital = 0;
double tauxEnDecimal = 0;
do {
annee++;
capitalDeDepart = capitalDeDepart + interet;
tauxEnDecimal = tauxInteretAnnuel / 100;
interet = capitalDeDepart * tauxEnDecimal;
nouveauCapital = (int)(capitalDeDepart + interet);
System.out.println(" " + annee + " " + (int)capitalDeDepart + "$ " + (int)interet + "$ " + (int)nouveauCapital + "$");
} while (annee != anneeTotalPlacement);
}
}
Indiquez le capital de départ : 10000
Inscrivez le taux d'intérêt annuel : 10
Indiquez la durée du placement en années :
Année Capital Intérêt Nouveau capital
----------------------------------------------
1 10000$ 1000$ 11000$
2 11000$ 1100$ 12100$
3 12100$ 1210$ 13310$
4 13310$ 1331$ 14641$
5 14641$ 1464$ 16105$
6 16105$ 1610$ 17715$
7 17715$ 1771$ 19487$
8 19487$ 1948$ 21435$
9 21435$ 2143$ 23579$
10 23579$ 2357$ 25937$

Just replase your System.out.println(...) with following:
System.out.format("%2d %5d$ %5d$ %5d$\n", annee,
(int)capitalDeDepart, (int)interet, (int)nouveauCapital);

you must will try add a String variable... like...
String reglerAnnee;
...
// add a space if year(anne) is less than 10
// using a ternary operator, like an "if" but less code
reglerAnnee = annee < 10 ? " " : "";
..
// and add to the println ...
System.out.println(" "+reglerAnnee + annee + " " + (int) capitalDeDepart
+ "$ " + (int) interet + "$ "
+ (int) nouveauCapital + "$");
...
The result will be like:
1 10000$ 1000$ 11000$
2 11000$ 1100$ 12100$
...
9 21435$ 2143$ 23579$
10 23579$ 2357$ 25937$

Related

SUM the result of a for LOOP java

So, I made a for loop with static and was working fine. But then I wanted to SUM the values of this loop to get the total value. But everytime I try to print it, I get the value 0. Any ideas? Please excuse the primitive coding.
I also have a Console class that I don't post but its from the Scanner class and is used for the "userInput".
Main class:
public class Main {
private static Console Consola;
public static void main(String[] args) {
ItemPower oco = new ItemPower();
CalculateThings oco2 = new CalculateThings();
System.out.println(Math.ceil(oco.preçoUnitarioVIII_II));
double unitariaT5 = Consola.userInput("Qual o Preço unitario da T5?");
double unitariaT4 = Consola.userInput("Qual o Preço unitario da T4?");
double unitariaCedarLog = Consola.userInput("Qual o Preço unitario da chedar Log?");
double desejadaT5 = Consola.userInput("Qual o Preço desejada de T5?");
System.out.println("Investimento em tier 5 Plank é de: " + oco2.tier5Plank(unitariaT5, desejadaT5));
System.out.println("Investimento em tier 4 Plank é de: " + oco2.tier4Plank(desejadaT5, unitariaT4));
System.out.println("Investimento em Chedar logs é de: " + oco2.chedarLog(desejadaT5, unitariaCedarLog));
System.out.println("value of totaT5 is " +oco2.totalT5);
CalculateThings.loopT5();
}
}
Class Calculate Things:
public class CalculateThings {
double unitariaT5;
double unitariaT4;
double unitariaCedarLog;
double desejadaT5;
double totalT5 = 0;
double totalT4 = 0;
double totalCH = 0;
public double tier5Plank(double desejadaT5, double unitariaT5){
return desejadaT5 * unitariaT5;
}
public double tier4Plank(double desejadaT5, double unitariaT4){
return desejadaT5 * unitariaT4;
}
public double chedarLog(double desejadaT5, double unitariaCedarLog){
return desejadaT5 * unitariaCedarLog * 3;
}
public double loopT5(double desejadaT5) {
for (int i = (int) desejadaT5; i >= 1; i = (int) (i * 0.367)) {
totalT5 += i;
}
return totalT5;
}
}
Thanks again for the help.
There are mainly 2 issues that I see here in the code attached.
First, you are not calling the loopT5() method with parameter. Also if you have already have instnace oco2 of CalculateThings, you can call the method like this
oco2.loopT5(desejadaT5);
or else you can do it like this
double d = new CalculateThings().loopT5(desejadaT5);
System.out.println("value of totaT5 is " +d);
Second, print statement should be after calling the loopT5().
You just need to replace these two lines as below.
System.out.println("value of totaT5 is " +oco2.totalT5);
CalculateThings.loopT5();
With below two lines.
oco2.loopT5();
System.out.println("value of totaT5 is " +oco2.totalT5);
For below code, i am able to get require output
class Main {
public static void main(String[] args) {
CalculateThings oco2 = new CalculateThings();
double unitariaT5 = 5;
double unitariaT4 = 4;
double unitariaCedarLog = 10;
double desejadaT5 = 15;
System.out.println("Investimento em tier 5 Plank é de: " + oco2.tier5Plank(unitariaT5, desejadaT5));
System.out.println("Investimento em tier 4 Plank é de: " + oco2.tier4Plank(desejadaT5, unitariaT4));
System.out.println("Investimento em Chedar logs é de: " + oco2.chedarLog(desejadaT5, unitariaCedarLog));
oco2.loopT5(5);
System.out.println("value of totaT5 is " + oco2.totalT5);
}
}
Output:
Investimento em tier 5 Plank é de: 75.0
Investimento em tier 4 Plank é de: 60.0
Investimento em Chedar logs é de: 450.0
value of totaT5 is 6.0

"Why does my lottery game ignores zeros?"

I'm doing exercice 3 from Chapter 4 of the book "Introduction to Java" by Walter Savitch.
Instructions:
Develop an algorithm for a simple game of guessing at a secret five-digit code. When the user enters a guess at the code the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code os 53840, and the user guesses 83241, the digits 3 and 4 are in the correct position. Thus, the program should respond 2 and 7. Allow the user to guess a fixed number of times
Current problems:
my code looks dirty and too long. I'm a beginner, but looking for ways to make it more efficient
when entering a 'guess number' that starts with any other number than 0 it works but when it starts with 0, my program ignores the first digit
I've spent two hours on it. There's still another 25 exercises waiting for me in this chapter only so I hope to be more efficient with the other exercises.
public static void main(String[] args) {
int SecretCode = 12140;
int Win = 0;
//just checking the incrementor
int sum = 0;
System.out.println("Ceci est un jeu de lotterie. \nPouvez-vous deviner le nombre à 5 chiffres caché ?\n");
Scanner fromPlayer = new Scanner(System.in);
do {
System.out.println("Votre nombre porte-bonheur: ");
int guess = fromPlayer.nextInt();
//Interprets Guess int to string
String stringGuess = String.valueOf(guess);
int length = stringGuess.length();
boolean CorrectLength = (length == 5);
if (CorrectLength) {
String Firstdigit = stringGuess.substring(0, 1);
String Seconddigit = stringGuess.substring(1, 2);
String Thirddigit = stringGuess.substring(2, 3);
String Fourthdigit = stringGuess.substring(3, 4);
String Fifthdigit = stringGuess.substring(4);
//Interprets Secret Code int to string
String stringSecretCode = String.valueOf(SecretCode);
String FirstdigitCode = stringSecretCode.substring(0, 1);
String SeconddigitCode = stringSecretCode.substring(1, 2);
String ThirddigitCode = stringSecretCode.substring(2, 3);
String FourthdigitCode = stringSecretCode.substring(3, 4);
String FifthdigitCode = stringSecretCode.substring(4);
//Just checking the values that the program will compare to secret code
System.out.println("Vous avez entré \n" + Firstdigit + "\n" + Seconddigit + "\n" + Thirddigit + "\n" + Fourthdigit + "\n" + Fifthdigit);
if (Firstdigit.equals(FirstdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Firstdigit);
System.out.println("Premier numéro est : correct. Score: " + Win);
} else {
System.out.println("Premier numéro est : incorrect. Score:" + Win);
}
if (Seconddigit.equals(SeconddigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Seconddigit);
System.out.println("Deuxième numéro est : correct. Score: " + Win);
} else {
System.out.println("Deuxième numéro est : incorrect. Score: " + Win);
}
if (Thirddigit.equals(ThirddigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Thirddigit);
System.out.println("Troisième numéro est : correct. Score: " + Win);
} else {
System.out.println("Troisième numéro est : incorrect. Score: " + Win);
}
if (Fourthdigit.equals(FourthdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Fourthdigit);
System.out.println("Quatrième numéro est : correct. Score: " + Win);
} else {
System.out.println("Quatrième numéro est : incorrect. Score: " + Win);
}
if (Fifthdigit.equals(FifthdigitCode)) {
Win = Win + 1;
sum = sum + Integer.parseInt(Fifthdigit);
System.out.println("Cinquième numéro est : correct. Score: " + Win);
} else {
System.out.println("Cinquième numéro est : incorrect. Score: " + Win);
}
System.out.println("Vous avez deviné " + Win + " numéros. Leur total vaut " + sum);
} else {
System.out.println("ERREUR. Il faut entrer 5 chiffres.");
}
I expect the output of 02140 to be
"Premier numéro est : incorrect. Score: 0
Deuxième numéro est : correct. Score: 1
Troisième numéro est : correct. Score: 2
Quatrième numéro est : correct. Score: 3
Cinquième numéro est : correct. Score: 4
Vous avez deviné 4 numéros. Leur total vaut 7"
BUT the actual output is: ERREUR. Il faut entrer 5 chiffres.
as if the program doesn't identify 0 as a digit.
Instead of using
String stringGuess = String.valueOf(guess);
you should use
String stringGuess = String.format("%05d", guess);
to always convert the number you've read into a five digit long String. In your current solution you should see that if you print stringGuess leading zeros will have been removed from the input.
Instead, you could use the following code which uses the nextLine() method of the Scanner class to solve your problem:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] expected = "53849".toCharArray();
// enter CTRL-D to stop
while (scanner.hasNext()) {
String input = scanner.nextLine();
if (input.length() != 5) {
System.err.println("wrong length");
continue;
}
char[] actual = input.toCharArray();
int digitSum = 0;
int correctDigits = 0;
for (int i = 0; i < expected.length; i++) {
if (actual[i] == expected[i]) {
correctDigits++;
digitSum += actual[i] - '0';
}
}
String msg = String.format(
"Number of correct digits: %d, their sum: %d",
correctDigits, digitSum
);
System.out.println(msg);
}
Try the one below and see if it works for you. Take the input directly into stringGuess instead of taking it into int and then converting it into String.
int guess = fromPlayer.nextInt(); //remove this and take input into the below variable directly
String stringGuess = fromPlayer.next();
Check this for your reference why the int cannot store leading zeroes.

java: loop produces incorrect output when reading from file?

This loop is producing the average values of hours and amount paid, but the output is mathematically incorrect. How can I edit this code to produce the correct average hours value and average paid values?
Scanner openFile = new Scanner(inFile);
while (openFile.hasNext()) {
if (openFile.hasNextDouble()) {
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble()) {
totalPaid += openFile.nextDouble();
numOfCharges++;
}
else {
openFile.next(); }
}
averageHours = (totalHours/numOfHourInputs);
averagePaid = (totalPaid/numOfCharges);
Below is my file:
The first column is unimportant for calculating the averages. The second column contains the numbers of hours. The third column contains the charges.
This file can have more data added to it by the user - the values inside of the file can be changed.
a 10.0 9.95
b 10.0 13.95
b 20.0 13.95
c 50.0 19.95
c 30.0 19.95
Remove the else:
else {
openFile.next(); //this consumes all input
}
The following code
Double[][] values = {{10.0, 9.95},
{10.0, 13.95},
{20.0, 13.95},
{50.0, 19.95},
{30.0, 19.95}};
Double totalHours = 0.;
int numOfHourInputs = 0;
Double totalPaid = 0.;
int numOfCharges = 0;
for (final Double[] value : values) {
totalHours += value[0];
numOfHourInputs++;
totalPaid += value[1];
numOfCharges++;
}
final double averageHours = (totalHours / numOfHourInputs);
System.out.println("averageHours = " + averageHours);
final double averagePaid = (totalPaid / numOfCharges);
System.out.println("averagePaid = " + averagePaid);
produced the result
averageHours = 24.0
averagePaid = 15.55
so that it's clearly not a mathematical problem. Check your input code especially for the line
openFile.next();
You still need to skip the first token but in the right spot:
public static void main(String[] args)
{
double totalHours = 0.0;
int numOfHourInputs = 0;
double totalPaid = 0.0;
int numOfCharges = 0;
Scanner openFile = null;
try
{
openFile = new Scanner(new File("c:\\temp\\pay.txt"));
}
catch (Exception e)
{
throw new RuntimeException("FNF");
}
try
{
while (openFile.hasNext())
{
// skip the first token
String token = openFile.next();
if (openFile.hasNextDouble())
{
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble())
{
totalPaid += openFile.nextDouble();
numOfCharges++;
}
}
}
finally
{
openFile.close();
}
double averageHours = (totalHours/numOfHourInputs);
double averagePaid = (totalPaid/numOfCharges);
System.out.println("Total hours: " + totalHours);
System.out.println("Num hours input: " + numOfHourInputs);
System.out.println("----------------------------------------");
System.out.println("Average hours: " + averageHours);
System.out.println("");
System.out.println("Total payments: " + totalPaid);
System.out.println("Num payments input: " + numOfCharges);
System.out.println("----------------------------------------");
System.out.println("Average paid: " + averagePaid);
}
Here is the output that I get:
Total hours: 120.0
Num hours input: 5
----------------------------------------
Average hours: 24.0
Total payments: 77.75
Num payments input: 5
----------------------------------------
Average paid: 15.55

The Java code did not show the result that I want

I am new to Java and actually this code is to ask the user for 2 numbers for the conversion from inch to centimeter and vice versa. But when I built it, it said "error: cannot find symbol" and I still cannot figure it out although I kept checking the code. Below is my code:
import java.util.Scanner;
import java.util.DecimalFormat;
public class Practical2Q2 {
public Practical2Q2() {}
public static void inchToCentimeter(double a) {
System.out.println("Inches " + "Centimeters");
System.out.print("\n");
for (double i = 1.0; i <= a; i++) {
double cm = i * 2.54;
System.out.println(i + " " + df.format(cm));
}
}
public static void centimeterToInch(double b) {
System.out.print("\n");
System.out.println("Centimeters " + "Inches");
System.out.print("\n");
for (double i = 5.0; i <= b; i += 5) {
double inch = i / 2.54;
System.out.println(i + " " + df.format(inch));
}
}
public static void main(String args[]) {
Scanner newScanner = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Please enter 2 numbers :\n" + "Number a for the conversion from inch to centimeter,\n"
+ "while number b for the conversion from centimeter to inch");
System.out.println("Number a : ");
double c = newScanner.nextDouble();
System.out.println("Number b : ");
double d = newScanner.nextDouble();
inchToCentimeter(c);
centimeterToInch(d);
}
}
Could you please state the wrong part?
You've created DecimalFormat df in the main method, it means that you can't access to it outside the method. I'v edited your code and i've created the field DecimalFormat df outside the main method.
I also changed the for loop inside the centimetersToInch() method, now it prints out all the values like in the inchToCentimeters() method.
Here's the code:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
static DecimalFormat df;
public static void inchToCentimeter(double a)
{
System.out.println("Inches " + "Centimeters");
System.out.print("\n");
for (double i = 1.0; i <= a; i++)
{
double cm = i * 2.54;
System.out.println(i + " " + df.format(cm));
}
}
public static void centimeterToInch(double b)
{
System.out.print("\n");
System.out.println("Centimeters " + "Inches");
System.out.print("\n");
for (double i = 1.0; i <= b; i++)
{
double inch = i / 2.54;
System.out.println(i + " " + df.format(inch));
}
}
public static void main(String args[])
{
Scanner newScanner = new Scanner(System.in);
df = new DecimalFormat("0.00");
System.out.println("Please enter 2 numbers :\n" + "Number a for the conversion from inch to centimeter,\n"
+ "while number b for the conversion from centimeter to inch");
System.out.println("Number a : ");
double c = newScanner.nextDouble();
System.out.println("Number b : ");
double d = newScanner.nextDouble();
inchToCentimeter(c);
centimeterToInch(d);
}
}
Your variable df is local only to your main method. Methods inchToCentimeter and centimeterToInch are unaware of this variable. Either make it a global variable or pass it as arguements to these methods.
Your df variable is not in there. Add the following line in your code.
static DecimalFormat df = new DecimalFormat("0.00");
Declare df variable as instance variable.

Java Powers display table

I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.
Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.
Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed
Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();
import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}

Categories

Resources