Printing out a while loop - java

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++;
}

Related

i compiled my java program and run in eclipse platform and also provide input but not got the output? There is any Logical Error in program [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
This is Selection Based Java Program. So in these program user have to provide the Vegetarian as V and Non-Vegetarian as N and it will take integer value for quantity and distance. So, when I saved and run the program it takes the value of the user parameter but didn't print the output I also check the errors in the eclipse editor.
#Program
'''
package demo;
import java.util.Scanner;
public class FoodCorner {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int vegCombo = 12;
int nonvegCombo = 15;
int totalCost = 0;
int charge = 0;
System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
String foodType = scan.nextLine();
System.out.println("Enter the Quantity of food Item");
int quantity = scan.nextInt();
System.out.println("Enter the Distance for delivery");
float distance = scan.nextFloat();
while(distance > 3) {
charge++;
distance = distance - 3;
}
if(distance > 0 && quantity >= 1) {
if(foodType == "V") {
totalCost = (vegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
else if(foodType == "N") {
totalCost = (nonvegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
}
else {
System.out.println("the bill amount is -1");
}
}
}
'''
Use below code snippet. Notice the line if("V".equals(foodType)) instead of if(foodType == "V").
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int vegCombo = 12;
int nonvegCombo = 15;
int totalCost = 0;
int charge = 0;
System.out.println("Enter the type of Food Item as Vegeterian 'V' and for Non-Vegeterian as 'N'");
String foodType = scan.nextLine();
System.out.println("Enter the Quantity of food Item");
int quantity = scan.nextInt();
System.out.println("Enter the Distance for delivery");
float distance = scan.nextFloat();
while(distance > 3) {
charge++;
distance = distance - 3;
}
if(distance > 0 && quantity >= 1) {
if("V".equals(foodType)) {
totalCost = (vegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
else if("N".equals(foodType)) {
totalCost = (nonvegCombo * quantity) + charge;
System.out.println("The total cost of your order is: "+totalCost);
}
}
else {
System.out.println("the bill amount is -1");
}
}

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();
}
}

Why does my Scanner input2 only record the the last input?

I am trying to create a college gpa calculator. The program first asks for the number of classes, the amount of credits for each class, and then for the grade for each class. The program works when the each class has the same amount of credits but does not work when there are different amounts of credits for each class. I have tried debugging the program by including print statements that show the values as the program runs and I have determined that credits only records the last inputted value. Is this just how .nextDouble() works or am I making a mistake? How would I go about fixing this problem? I am also fairly new to Java so if I am making a simple mistake there's a reason why.... Thanks
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("This program calculates your college GPA.");
System.out.println("Enter the number of classes you've taken this quarter/semester:");
int classes;
classes = input.nextInt();
double gradePoint = 0;
double credits = 0;
double totalCredits = 0;
String grades;
double gpa = 0;
double total = 0;
// for loop record number of credits per class
for (int i = 0; i < classes; i++) {
Scanner input2 = new Scanner(System.in);
if (i > 0) {
// user will be asked this second
System.out.println("Enter next amount of credit hours:");
}
else {
// user will be asked this first
System.out.println("Enter the number of credits for each class one by one:");
}
credits = input2.nextDouble();
System.out.println("credits:" + credits);
totalCredits += credits;
System.out.println("totalcredits:" + totalCredits);
}
System.out.println("credits:" + credits);
// for loop to record grades input and calculate gpa
for (int b = 0; b < classes; b++) {
System.out.println("credits:" + credits);
Scanner input3 = new Scanner(System.in);
if (b > 0) {
System.out.println("Enter your next grade:");
}
else {
System.out.println("To receive your GPA, enter your grades one by one:");
}
grades = input3.nextLine();
// if statements will convert letter grades to grade points
// grade points will then be multiplied by their respective amount of credits
if (grades.equals("A+")) {
gradePoint=4.0;
total += (gradePoint*credits);
}
else if (grades.equals("A")) {
gradePoint=4.0;
total += (gradePoint*credits);
}
else if (grades.equals("A-")) {
System.out.println("credits:" + credits);
gradePoint=3.7;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("B+")) {
System.out.println("credits:" + credits);
gradePoint=3.3;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("B")) {
System.out.println("credits:" + credits);
gradePoint=3.0;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("B-")) {
System.out.println("credits:" + credits);
gradePoint=2.7;
System.out.println("gradePoint:" + gradePoint);
total += (gradePoint*credits);
System.out.println("total:" + total);
}
else if (grades.equals("C+")) {
gradePoint=2.3;
total += (gradePoint*credits);
}
else if (grades.equals("C")) {
gradePoint=2.0;
total += (gradePoint*credits);
}
else if (grades.equals("C-")) {
gradePoint=1.7;
total += (gradePoint*credits);
}
else if (grades.equals("D+")) {
gradePoint=1.3;
total += (gradePoint*credits);
}
else if (grades.equals("D")) {
gradePoint=1.0;
total += (gradePoint*credits);
}
else if (grades.equals("D-")) {
gradePoint=0.7;
total += (gradePoint*credits);
}
else if (grades.equals("F")) {
gradePoint=0;
total += (gradePoint*credits);
}
else {
System.out.println("Invalid input.");
}
// gpa algorithm
gpa = total/totalCredits;
System.out.println("totalCredits" + totalCredits);
System.out.println("gpa:" + gpa);
}
System.out.println("GPA: " + gpa);
}
}
Also, when inputted:
3
5
5
3
A+
B+
C-
The program outputs the following:
This program calculates your college GPA.
Enter the number of classes you've taken this quarter/semester:
3
Enter the number of credits for each class one by one:
5
credits:5.0
totalcredits:5.0
Enter next amount of credit hours:
5
credits:5.0
totalcredits:10.0
Enter next amount of credit hours:
3
credits:3.0
totalcredits:13.0
credits:3.0
credits:3.0
To receive your GPA, enter your grades one by one:
A+
totalCredits13.0
gpa:0.9230769230769231
credits:3.0
Enter your next grade:
B+
credits:3.0
gradePoint:3.3
total:21.9
totalCredits13.0
gpa:1.6846153846153844
credits:3.0
Enter your next grade:
C-
totalCredits13.0
gpa:2.076923076923077
GPA: 2.076923076923077
(the correct gpa should be 3.2)
The problem in your credits variable, when you input
5
5
3
the last input which is 3 is stored into your credits variable and the same value is going through your 2nd loop which you're using for grades.
Solution 1:
Use array credits array and input your all classes credits into this array so that you can access different credits into your grades inputs.
Solution 2:
Use only one loop for credits and grades and input one by one I make some code for you.
here is the code.
for (int b = 0; b < classes; b++) {
Scanner input3 = new Scanner(System.in);
System.out.println("Enter credit hours for class :"+(b + 1));
credits = input2.nextDouble();
System.out.println("credits:" + credits);
totalCredits += credits;
System.out.println(" ");
System.out.println("Enter grade for class : "+(b + 1));
grades = input3.nextLine();
}
Inputs:
3 //number of classes
5 //first class credits
A+ //first class grade
5 .
B+ .
3 .
c- ..........
Output:
gpa:3.2
GPA: 3.2

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

how to change user input from integer to decimal

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";
}

Categories