how to change user input from integer to decimal - java

I'm new to java and was wondering how to change a user input (integer) into decimal form. for ex, if the user inputs 6 for yearly interest, it will be changed to 0.06 before the calculations are done and the answer is printed.
this program is just used to determine how long a bank account will last.. but I am also supposed to print this in a year and month format. I'm not sure how to do that, except to put in another if statement and say if (answer from the above calculations > 12) subtract 12 from the calculations and add1 to year.. and somehow put that in a loop.
if anyone has advice/pointers to give on doing this it'd really be helpful!
import java.util.*;
class Two {
public static void main(String[] args) {
Scanner imp = new Scanner(System.in);
System.out.print("Enter your initial balance: ");
double bal = imp.nextDouble();
System.out.print("Enter your yearly interest: ");
double intr = imp.nextInt();
System.out.print("Enter your monthly withdrawls: ");
double wtd = imp.nextDouble();
if (true) { //need to change
System.out.print("Your account will last " + (((bal*intr) + bal)/ wtd) + " months");
} else { System.out.print("The account will last forever");
}
}
}

you can multiply with 0.01 (this avoids the explicit cast though the conversion from int to double needs to happen somehow)
double intr = imp.nextInt()*0.01;
and to transfer months into years + months check out integer division and the modulo operator
int months = 18;//calculated
int years = month/12;//integer division is a implicitly rounded down
months = months%12;
or if you really need to make a loop
int months = 18;//calculated
int years = 0;
while(months >= 12){
months -= 12;
years += 1;
}

Try
double intr = ((double)imp.nextInt()/100);
EDIT
Oops, I missed that nested question. See How to convert months to years-and-months.

You want to convert to percentage, so you'll have to divide by 100. Here is a possible solution:
double intrAsDouble = ((double)intr)/100;
Oh, and as for the date thing:
int totalMonths = ((bal*intrAsDouble) + bal))/wtd;
int years = (int)(totalMonths/12);
int months = totalMonths%12;
String accountWillLast = "";
boolean hasMonths = months != 0;
boolean hasYears = years != 0;
if (hasYears) {
accountWillLast = accountWillLast + years;
if (years == 1) accountWillLast = accountWillLast + " year";
else accountWillLast = accountWillLast + " years";
}
if (hasMonths && hasYears) {
accountWillLast = accountWillLast + " and ";
}
if (hasMonths) {
accountWillLast = accountWillLast + months;
if (months == 1) accountWillLast = accountWillLast + " month";
else accountWillLast = accountWillLast + " months";
}

Related

Java, something wrong with Double data type, keep returning 1.00 instead of 1.8 [duplicate]

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I am working on a project for my college, so far code is working fine, except when a program tries to calculate the average all input, it always gives the wrong answer.
Ex:
Test input:
3
-4
5
12
-7
0 (to exit the loop)
Result ->
sum: 9
Counter: 5
Average = 1.0 ? It should be 1.8
If anyone could help, please give me some advice.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int counter = 0;
int intInput;
int intLargest;
int intSmallest;
int intEven = 0;
int intOdd = 0;
int intSum = 0;
String strMessage = "Enter a series of value (0 to quit)";
System.out.print(strMessage);
System.out.println();
System.out.print("Enter Integer value?" + "\n");
intInput = sc.nextInt();
intLargest = intInput;
if (intLargest == 0)
{
intLargest = 0;
}
else
{
intLargest = intInput;
}
/////////////////////////////////////////////////////////////
intSmallest = intInput;
if (intSmallest == 0)
{
intSmallest = 0;
}
else
{
intSmallest = intInput;
}
while(intInput != 0)
{
{
if (intInput > intLargest)
{
intLargest = intInput;
}//Get the largest value
else if (intInput < intSmallest)
{
intSmallest = intInput;
}//Get the smallest value
if ((intInput%2) == 0)
{
intEven++;
}//Get number of Even value
else if ((intInput%2) != 0)
{
intOdd++;
}//Get number of Odd value
}
intSum = intSum + intInput;
intInput = sc.nextInt();
counter++;
}
/********************************************/
double doubleAvg = 0;
if (counter > 0)
{
doubleAvg = intSum / counter;
}
/***************************************************/
System.out.println();
System.out.print("Smallest = " + intSmallest +"\n");
System.out.print("Largest = " + intLargest + "\n");
System.out.print("Total Entered = " + counter + "\n");
System.out.print("Even Number = " + intEven + "\n");
System.out.print("Odd Number = " + intOdd + "\n");
System.out.print("Average = " + doubleAvg + "\n");
System.out.print("SUM: " + intSum + "\n");
}
}
Both intSum and counter are declared as int. And in case of dividing int by int the result will also be int. So result of division is 1 and then it is converted to double and you get 1.0. To get correct result declare intSum as double.

How do I write a loop that prints the year and balance?

Scanner console = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
Double balance = Double.parseDouble(console.nextLine());
System.out.println("Enter Yearly Contribution: ");
Double cont = Double.parseDouble(console.nextLine());
System.out.println("Enter Average Return On Investment as %: ");
Double avg = Double.parseDouble(console.nextLine());
System.out.println("Enter Number of years: ");
int year = Integer.parseInt(console.nextLine());
double result1 = (balance + cont) * (1 + avg / 100);
double result2 = (result1 + cont) * (1 + avg / 100);
year = 0;
while (year <= year) {
System.out.println("Year " + year + ": " + balance + "");
year = year + 1;
for (result2 = result2; result2 >= result2; result2 = result2 + result2) {
}
//I am aware that the loop is wrong, just not sure the best way to write it.
So provided there isn't a whole lot of detail, I wrote this code which results in output very close to the example you provided. Modify it as needed to match your desired output.
package various;
import java.util.Scanner;
public class Balance {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
double balance = sc.nextDouble();
System.out.println("Enter Yearly Contribution: ");
double cont = sc.nextDouble();
System.out.println("Enter Average Return On Investment as %: ");
double avg = sc.nextDouble();
System.out.println("Enter Number of years: ");
int years = sc.nextInt();
double temp = 0;
for(int i = 0; i <= years; i++) {
double result = balance + (i*cont)+ (i*temp*(avg/100));
temp = result;
System.out.println("Year "+i+": "+result);
}
sc.close();
}
}

How to fix NoSuchElementExeption in Java [duplicate]

This question already has answers here:
Why is this code getting a Java NoSuchElement exception?
(3 answers)
Closed 5 years ago.
I've made a simple game with 2 classes. It uses a scanner and when I try it it says java.util.NoSuchElementExeption. It also says the errors are on row 19 in RNGlog and 24 in RNG. Please help
First class: RNG
public class RNG {
public static void main(String[] args) {
RNGlog log = new RNGlog();
int max = log.max();
int min = log.min();
double counter = 3;
//Variables outside of loop
System.out.println("Write a number between " + max + " and " + min + ".");
System.out.println("If your number is higher than " + max + ", it will be " + max + ". Vice versa for " + min + ".");
System.out.println("If your number is higher than the random number, you win credits!");
System.out.println("You start with 2 credits.");
System.out.println("You lose if you hit 0 credits. Good luck!");
//Introduction
while(counter > 0) {
//Loop start
double r = Math.random() * 10;
float in = log.getIn(); //Error here
//Random number generator, input
double credit = 6 - in;
//Credit Win generator
if(in > r) {
counter = counter + credit;
//Counter refresh
System.out.println("Great job! The number was " + r + ".");
System.out.println("You won " + credit + " credits. Nice.");
System.out.println("Credit counter:" + counter + ".");
//Winning messages
}
else {
counter = counter - 1;
//Counter refresh
System.out.println("Nearly, n00b! It was " + r + ", how did u no realize.");
System.out.println("You lost 1 credits!");
System.out.println("Credit counter:" + counter + ".");
//Losing messages
}
if(counter <= 0) {
System.out.println("Game over! Better luck next time.");
//Game ender
}
}
}
}
Second class: RNGlog
import java.util.Scanner;
public class RNGlog {
int max() {
int max = 6;
return max;
}
int min() {
int min = 0;
return min;
}
float getIn() {
Scanner scan = new Scanner(System.in);
float imp = scan.nextFloat(); //Error here
if(imp < min()) {
imp = min();
}
//Stops number lower than 0
if(imp > max()) {
imp = max();
}
//Stops numbers higher than 6
scan.close();
return imp;
}
}
Would be really apriciated if someone could help!
NoSuchElementException : if the input is exhausted
you must test before with scanner.hasNext()
and if (scan.hasNextFloat())

My program has no syntax error but I can't get the final avg # right

My program has no syntax error, I can input all the value, but I just can't get the final average number right. Can anyone help me find out the problem?
The following is what I input:
How many employees do you have? 4
How many days was Employee #1 absent? 4
How many days was Employee #2 absent? 2
How many days was Employee #3 absent? 1
How many days was Employee #4 absent? 3
Final answer should be: 2.5
This is the code I use:
import java.util.Scanner;
class Number {
public static void main(String[] args) {
int numEmployee = Number.workers();
int absentSum = Number.totaldays(numEmployee);
double averageAbsent = Number.average(numEmployee, absentSum);
}
public static int workers() {
int number = 0;
Scanner input = new Scanner(System.in);
while (number > 0 || number < 0 || number == 0) {
System.out.println("How many employees do you have?");
number = input.nextInt();
if (number >= 0) {
return number;
} else {
System.out
.println("You can not enter a negative number."
+ " Please enter another number.");
}
}
return number;
}
public static int totaldays(int numEmployee) {
int absentDays = 0;
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
return absentSum;
}
public static double average(int numEmployee, int absentSum) {
double averageAbsent = (double) absentSum / (double) numEmployee;
System.out.println("Your employees averaged " + averageAbsent
+ " days absent.");
return averageAbsent;
}
}
Move absentSum += absentDays; into the loop body in totaldays. If you restrict the visibility of absentSum then the compiler will tell you that you are accessing it out of scope. Something like
public static int totaldays(int numEmployee) {
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
int absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
// absentSum += absentDays;
return absentSum;
}
With the above output (and your provided input) I get (the requested)
2.5

Printing out a while loop

import java.util.Scanner;
public class Teacher{
public static void main(String [] args){
Scanner reader = new Scanner(System.in);
double salary;
double pi;
int year;
int years = 1;
double predict;
double predict2 = 0;
double sum = 0;
System.out.print("What is your starting salary: ");
salary = reader.nextDouble();
System.out.print("What is your precentage increase: ");
pi = reader.nextDouble();
System.out.print("How many years are you working: ");
year = reader.nextInt();
if (salary <= 0){
System.out.print("The salary must be positive.");
}
if (pi <= 0){
System.out.print("The percentage increase must be positive.");
}
if (year < 0){
System.out.print("The years must be positive.");
}
while (year > years) {
predict = salary * (pi/100);
System.out.println(years + ". " + predict);
years++;
if (years == year){
break;
}
}
}
}
I am having trouble trying to print out a loop. Every time I run the program, this segment only prints out one number and doesn't print out the rest.
per #ajb wouldn't you want to do something like this in your loop? This will print your salary increase every year, and also add that to the salary for the next iteration
Per your new comment
Every time their is an output, I would like it to display the year and
their salary.
while (year > years) {
//predict = salary * (pi/100); commented this because it is not necessary anymore.
salary += salary * (pi/100);
System.out.println(years + ". " + salary); // replaced predict with salary, to show their salary and not just their predicted raise.
years++;
// This block of code will never be hit, therefore it is not needed.
//if (years == year){
// break;
//}
}
Revised could be something like this.
while (year > years) {
salary += salary * (pi/100);
System.out.println(years + ". " + salary);
years++;
}

Categories