Ive been working on this program for a few days now and its due tonight at midnight. I cannot for the life of me figure out why I keep getting a " The local variable cannot be initialized" error. This is my first coding class and I do not understand it very well. If someone could help me out by explaining a fix and why this error keeps happening that would be great.
I have put "**" where the errors are ( near the end of the code). Any help would be great! Thanks in advance.
/*This program will determine how much the students
tuition and fees are based on location and classes. It will return the
total tuition, fees, and combined total */
import java.text.DecimalFormat;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//Declaring variables and decimal format
int TotalHours;
int Price;
int CreditCharge;
int CITFee;
int OnlineFee;
int INFCSCFee;
int TotalTuition;
int TotalFee;
int TotalCombined;
DecimalFormat df = new DecimalFormat("$#,###");
//Getting the students First name, Last name, and Date
System.out.print("Enter your first name: ");
String FirstName = in.nextLine();
System.out.print("Enter your last name: ");
String LastName = in.nextLine();
Date d = new Date ( );
//Getting the state of residency. If in Ohio, asking the user if they are Metro
System.out.print("Enter your State of residency as a 2-letter abbreviation: ");
String State = (in.next().toLowerCase());
if (State.equals ("oh") || State.equals("OH")){
System.out.print( "Are you a Cincinnati resident? (Y/N) ");
String Metro = in.next();
if (Metro.equals ("y")) Price = 567;
}
else Price = 750;
if (State.equals ("ky") ){ Price = 375;
}
else if (State.equals ("in")){Price = 375;
}
else {Price = 750;
}
//Getting the number of credit hours the student is taking
System.out.print("Enter the total credit hours for the upcoming semester: ");
TotalHours = in.nextInt();
if (TotalHours <= 12) CreditCharge = (TotalHours * Price);
else {CreditCharge = (Price * 12);
}
//Getting the number of CIT hours the student is taken
System.out.print("Enter the total of CIT credits you are taking: ");
int TotalCITHours = (int) in.nextInt();
CITFee = (TotalCITHours * 40);
//Getting the number of online credit hours the student is taken
System.out.print("Enter the total number on-line credit hours you are taking: ");
int OnLine = (int) in.nextInt();
OnlineFee = (OnLine * CITFee * 35);
//Seeing if the student is taken either INF 120 or CSC 260
System.out.print("Are you taking either INF 120 or CSC 260? (Y/N) ");
String INFCSC = in.next().toLowerCase();
if (INFCSC.equals ("y")) INFCSCFee = (char) (CITFee * OnlineFee + 60);
//Calculating the tuition, fees, and total combined.
** TotalTuition = CreditCharge;
** TotalFee = INFCSCFee;
** TotalCombined = TotalTuition + INFCSCFee;
//Tuition Statement for FirstName, LastName, Date
System.out.println("\nTuition Statement for " + FirstName + LastName);
System.out.println(d);
System.out.println("Tuition: " + df.format (TotalTuition) );
System.out.println("Fees: " + df.format(TotalFee));
System.out.println("Total: " + df.format(TotalCombined));
}
}
Your variable INFCSCFee was not initialized if they did not answer yes to the question "Are you taking either INF 120 or CSC 260? (Y/N) ". Eclipse will not let you run the program if a variable may not have been initialized. At the top of your code where you have
int INFCSCFee;
replace it with
int INFCSCFee = 0;
or initialize the variable somewhere else or with some other value.
Here is the fault
if (INFCSC.equals ("y")) INFCSCFee = (char) (CITFee * OnlineFee + 60);
This is the only place INFCSCFee can be initialised. So it is possible therefore that it has not been initialised by the time it is used. More generally, this is not allowed:
int x; // declare x - not yet initialised
if (someCondition)
x = 3; // initialise to 3
// if somecondition was false, x is still unitialised
System.out.println("x is "+x); // Error
You cannot use a variable declared in a method unless the compiler can gaurantee it has been initialised beore you us it. This would be allowed:
int x; // declare x - not yet initialised
if (someCondition)
x = 3;
else if (somethingElse)
x = 4;
else
x = 5;
// For all outcomes, x has been initalised, so it is safe to use
System.out.println("x is "+x);
This is allowed too:
int x; // declare x - not yet initialised
if (someCondition)
x = 3;
else
return;
// Although someCondition may have been false, if we reach this line of
// code, it is because someCondition was true and therefore x was initialised
System.out.println("x is "+x); // will print x is 3
Finally, you can initalise your variable at declaration time:
int x = 0;
Now, wherever x is used, it is gauranteed to be initalised, so you won't get a compile error. That's not necessarily a good thing, because that compiler error could actually be showing you a bug in your code, and you've suppressed it by giving the variable a default value.
Related
I'm currently working on a GPA calculator for a class of mine. I keep getting an error that has to do with the division I'm trying to do on the GPA calculation and am having trouble with the syntax for sub-strings and how to use them correctly. Below is the code I have so far. If you see anything I can fix that's not to complicated I'm open to all suggestions.
import java.util.Scanner;
public class GPA
{
public static void main(String[] mydata)
{
Scanner sc = new Scanner(System.in);
String choice = "";
String cnum;
String grade;
double points;
double gpa = 0;
int count = 0;
String credit= "", totalCredit = "";
while (!choice.equalsIgnoreCase("Q"))
{
cnum = (mydata[0]);
grade = (mydata[1]);
if (grade.equalsIgnoreCase("A")) {points = 4.0;}
else if (grade.equalsIgnoreCase("B")) {points = 3.0;}
else if (grade.equalsIgnoreCase("C")) {points = 2.0;}
else if (grade.equalsIgnoreCase("D")) {points = 1.0;}
else if (grade.equalsIgnoreCase("F")) {points = 0.0;}
credit = cnum.substring(3,4);
//System.out.println("credits = " + totalCredit);
System.out.println("GPA = " points/Double.parseDouble(credit));
System.out.print("Enter next course number and grade or ‘Q’ to quit: ");
System.out.println();
choice = sc.nextLine();
}
System.out.println("Bye!");
}
}
Not bad but there are a couple syntactical errors with your code:
The println argument needs to be concatenated with a +:
System.out.println("GPA = " + points / Double.parseDouble(credit));
The local variable, points, needs to be initialized since your if-else conditions are not exhaustive (ie: grade has a runtime range of A, B, C, D, or F but grade can technically be assigned to whatever is in mydata[1]). Either add an else condition or assign an initial value to points:
double points = 0.0;
Be sure to include + to concat the strings together :)
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
I believe you want to be concatenating here.
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
Instead of
System.out.println("GPA = " (points/Double.parseDouble(credit)));
And if you want
int theGpa = points/Double.parseDouble(credit));
System.out.println("GPA: " + theGpa);
I have just started learning Java in the last week or so and I'm creating a program that acts as a sales calculator that calculates commission.
My code is as follows:
import java.util.Scanner;
public class Application {
int itemOne;
int itemTwo;
int itemThree;
int itemFour;
final double baseCommission = 200;
final double itemOnePrice = 239.99;
final double itemTwoPrice = 129.75;
final double itemThreePrice = 99.95;
final double itemFourPrice = 350.89;
final double commissionPercentage = 0.09;
boolean startLoop = false;
public void start(){
while (startLoop = false);
{
//Welcome message
System.out.println("Welcome to Devon's Sales Calculator!");
//Defining new scanner
Scanner user_input = new Scanner(System.in);
//Getting user input for salesperson name along with number of items sold as well as assigning them to a variable
String salesman_name;
System.out.print("Insert salesperson name:\t");
salesman_name = user_input.next();
System.out.print("Enter number of first item sold:\t");
int first_item = user_input.nextInt();
System.out.print("Enter number of second item sold:\t");
int second_item = user_input.nextInt();
System.out.print("Enter number of third item sold:\t");
int third_item = user_input.nextInt();
System.out.print("Enter number of fourth item sold:\t");
int fourth_item = user_input.nextInt();
//Printing out the name of the salesmen, followed by the total price of items sold
System.out.println("Sales Person\t" + salesman_name);
System.out.println("Total price of first item sold\t" + first_item * itemOnePrice);
System.out.println("Total price of second item sold\t" + second_item * itemTwoPrice);
System.out.println("Total price of third item sold\t" + third_item * itemThreePrice);
System.out.println("Total price of fourth item sold\t" + fourth_item * itemFourPrice);
//Calculating total of all items sold
double finalPrice = first_item * itemOnePrice + second_item * itemTwoPrice + third_item * itemThreePrice + fourth_item * itemFourPrice;
//Calculating commission # 0,9%
System.out.println("Total commission earned\t" + finalPrice * commissionPercentage);
//Decision whether or not to restart the while loop
String decision;
System.out.println("Would you like to check another salesperson?");
decision = user_input.next();
if(decision == "yes"){
startLoop = false;
}
else if(decision == "no"){
startLoop = true;
}
}
}
}
Whenever I execute my while loop, it doesn't restart to choose another salesman. I'm probably doing something horribly wrong and my code formatting is probably horrible. Any help would be appreciated.
Get rid of the = false and the semicolon. So not:
while (startLoop = false);
{
System.out.println("foo");
}
which is equivalent to
while (startLoop = false) {
// do nothing
}
{
System.out.println("foo");
}
Instead do,
while (!startLoop) {
// do something here
}
Im trying to write a code, that computes CD value, for every month.
Suppose you put 10,000 dollars into a CD with an annual percentage yield of 6,15%.
After one month the CD is worth:
10000 + 10000 * 6,15 / 1200 = 10051.25
After the next month :
10051.25 + 10051.25 * 6,15 / 1200 = 10102.76
Now I need to display all the results for the specific number of months entered by the user,
So
month1 =
month2 =
But whth this code I wrote, nothing is printed.
Can you see what's wrong?
Thanks in advance!
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
while (i != months) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
You do not modify neither i nor months in
while (i != months) {
....
}
so if the (i != months) condition is satisfied, the loop runs forever, and you never get to System.out.print statement.
for (int i = 1; i < months; i++) {
while (i != months) {
//you have to modify i or to modify the while condition.
}
if you don't modify i in the while you can't exit from the loop
Corrected code-
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i <= months; i++)
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
}
Note: If you want to print values for each month then the print statement should be inside the loop. You don't need two loops for the objective that you have mentioned above.
As you have been told your code won't get out of the while loop if you don't modify it. Simply remove the while loop. Your code should be like this:
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextDouble();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
}
}
Thanks! Solved it by using
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
instead of while loop.
It works now :) Thanks so much!
My program is nearly done except for one problem. I'm having an out of scope problem with the for loop. The goal of the program is to compound monthly interest for a user inputted amount & term.
An example of output at $5000 principal with 5% interest for 3 years would be:
Month: Interest: Principal:
1 $20.83 $5020.83
2 $20.92 $5041.75
etc etc etc
Starting Balance = $ 5000.00 // having problem outputting these w/ for-loop
Final Account Balance = $ 5807.36 // System.out.print keeps repeating multiple times
Total Interest Paid = $ 807.36 // but i can't use variables outside of loop
My problem is that during my for loop, I keep outputting Starting Balance, Final Balance and Total Interest every time the program goes through the loop. but if I try to use the variables outside the loop it goes out of scope and if I try to declare variables outside of the loop I can't use them inside the loop because it's already been declared in the constructor.
Can anyone give me some hints or advice?
My code:
public class Calculator
{
public Calculator()
{
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error){
System.out.print("Please input the following: principal, interest rate, term >> ");
double principal = input.nextDouble();
double interest_rate = input.nextDouble();
int term = input.nextInt();
String Month = input.next();
char dollar_sym = 36;
if (interest_rate <= 0 || term <= 0 || principal <= 0) // input validation
{
System.out.println("The term, interest rate and principal must be greater
than zero");
continue;
}
if (!Month.equals("month")) // input validation
{
System.out.println("Please input month after term");
continue;
}
System.out.println("Month: " + " Interest: " + "Principal: ");
if (Month.equals("month"))
{
for (int month = 1; month <= term; month++)
{
double interest = (principal * interest_rate / 100) / 12;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month,
dollar_sym, interest, dollar_sym, principal );
double start_principal = principal - interest; // problem
double final_principal = principal; // problem
double total_interest = interest * interest_rate; // problem
System.out.println(" Starting balance = " + start_principal ); // problem
System.out.println("Final account balance = " + final_principal ); // problem
System.out.println("Total Interest Paid = " + total_interest); // problem
}
}
}
}
}
Declare them before the loop begins, so they will exist inside the loop and after it:
double start_principal = 0;
double final_principal = 0;
double total_interest = 0;
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error) {
// ...
}
// ...
In my answer, I am assuming that when you say goes out of scope, you mean that you get a compile time error. (note, it would make the answer easier to address if you provided the error message and the line that is causing the error message).
The scope of a variable refers to where the variable is accessible. For example, if you declare a variable inside of an if statement, the scope is that if statement. Some example code:
public void updateStatus(){
Boolean shouldCheckStatus = true;//this variable is declared inside of the updateStatus method, so that is the scope of the variable
if(shouldCheckStatus == true){
Int hitCounter = 0;//this variable is declared inside of the if statement, so it is only accessible inside of the if statement
//do some work
if(hitCounter > 100){
self.registerHits(hitCounter);//hitCounter is still accessible here, because it is still inside of the if statement
}
else{
shouldCheckStatus = false;
}
}//close the if statement and so close the scope...
//the hitCounter variable is no longer in scope, because we are no longer in the if statement
//but shouldCheckStatus is still in scope, because we are still in the method
if(shouldCheckStatus == true){
self.callAnotherMethod();
}
}
So in your problem, you need to declare your variable above where you want to use it, inside of the scope that you want to use it. And then not declare it again. So declare before the loop.
I'm a college freshmen and I'm having trouble with my programming homework. The homework I got from my lecturer was for me to write a program in Java to take in a student's info, and allow the student to choose how many subject the student takes, and input marks and credit hours, followed by a formula to calculate the grade and subject grade points. In the end of the program, the program would be able to output the student info (name, ID etc) and the total subject grade point for all of the subjects entered, total credit hours for all the subjects, and the cumulative grade point average (CGPA).
However, I have three problems here
I have an issue with the loop that I have set in order to read how many subjects the user wants to key in.
When I tried to print "Grade = " + subjectGrade); my compiler says it hasn't been initialized. Same goes to the GradePoint and subjectCreditHour.
And I couldn't figure out how to get the program to calculate the Total Subject Grade Points, Total Credit Hours, and CGPA. Because depending on how many numbers of subjects the user wants, I can't figure out how to get the program to take in the user's input and sum them up together
My code goes like this :
package javaquiz1;
import java.util.Scanner;
/**
*
* #author jerem_000
*/
public class JavaQuiz1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String name;
int ID;
int tel;
String email;
int subjects;
String subjectName;
int subjectCreditHour;
int subjectMark;
String subjectGrade;
double GradePoint;
double subjectGradePoint;
double CGPA;
double totalSubjectGP;
int totalCreditHour;
System.out.print("Please input student's name : ");
name = input.nextLine();
System.out.print("Please input student's ID : ");
ID = input.nextInt();
System.out.print("Please input student's telephone number : ");
tel = input.nextInt();
System.out.print("Please input student's email : ");
email = input.next();
System.out.print("Please input number of subjects : ");
subjects = input.nextInt();
for (int i = 1; i >= subjects ; i++) { //I'm having an issue with this loop
System.out.println("Subject " + i + " : Please input the following"); //I placed the variable i there in order to make the program print something like "Subject 1 , Subject 2, Subject 3 etc". Depending on the user's number of subjects input
System.out.print("Subject name : ");
subjectName = input.next();
System.out.print("Credit Hour : ");
subjectCreditHour = input.nextInt();
System.out.print("Mark : ");
subjectMark = input.nextInt();
if ( subjectMark >= 80 ) {
subjectGrade = "A";
GradePoint = 4.0;
} else if (subjectMark < 80) {
subjectGrade = "B+";
GradePoint = 3.5;
} else if (subjectMark < 70) {
subjectGrade = "B";
GradePoint = 3.0;
} else if (subjectMark < 65) {
subjectGrade = "C+";
GradePoint = 2.5;
} else if (subjectMark < 55) {
subjectGrade = "C";
GradePoint = 2.0;
} else if (subjectMark < 50) {
subjectGrade = "D";
GradePoint = 1.0;
} else {
subjectGrade = "F";
GradePoint = 0.0;
}
}
System.out.println("Grade = " + subjectGrade);
System.out.println("Subject Grade Point = " + (GradePoint * subjectCreditHour)); //I'm having a problem with the subjectGrade, GradePoint, and subjectCreditHour, it says variable might have not been initialized
System.out.println("Name : " + name);
System.out.println("ID : " + ID);
System.out.println("Tel : " + tel);
System.out.println("email : " + email);
System.out.print("Total subject Grade Points = " );
System.out.print("Total Credit Hours = " );
System.out.print("Cumulative Grade Point Average ="); //On this 3 system.out.prints, I can't seem to think of a way to read the Grade Point, Total Credit Hours, and CGPA, and add them all together
}
}
I also have a sample output on how the program is supposed to be:
Please input student's name : James Cook
Please input student's ID : 0106578
Please input student's tel : 010783938
Please input student's e-mail : jcook#gmail.com
Please input number of subjects : 3
Subject 1 : Please input the following
Subject name : Fundamentals of Programming
Credit Hour : 4
Mark : 78
Grade : B+
Subject Grade Point : 14.0
Subject 2 : Please input the following
Subject name : English
Credit Hour : 3
Mark : 85
Grade : A
Subject Grade Point : 12.0
Subject 3 : Please input the following
Subject name : Computer Fundamentals
Credit Hour : 3
Mark : 78
Grade : B+
Subject Grade Point : 10.5
Name : James Cook
ID : 0106578
tel : 010783938
e-mail : jcook#gmail.com
Total subject Grade Point = 36.5
Total Credit Hours = 10
CGPA = 3.65
The formula to calculate the subject grade point is
subjectGradePoint = GradePoint * CreditHour
And the formula to calculate the CGPA (cumulative grade point average) is
CGPA = totalSubjectGP / totalCreditHours
Correction, criticism, advice will be welcomed for future improvement. Thanks in advance!
1) I have an issue with the loop that I have set in order to read how
many subjects the user wants to key in.
Already answered by #Nishan in a comment. Just replace for (int i=1;i >= subjects; i++) by for (int i=1;i <= subjects; i++).
2) When I tried to print "Grade = " + subjectGrade); my compiler says it
hasn't been initialized. Same goes to the GradePoint and
subjectCreditHour.
Already answered.
3) And I couldn't figure out how to get the program to calculate the
Total Subject Grade Points, Total Credit Hours, and CGPA. Because
depending on how many numbers of subjects the user wants, I can't
figure out how to get the program to take in the user's input and sum
them up together
You already are on the right way since you have the accumulators you need:
double subjectGradePoint = 0d;
double CGPA = 0d;
double totalSubjectGP = 0d;
int totalCreditHour = 0;
Whitin your loop and after nested if-else blocks, you need to update subjectGradePoint, totalSubjectGP and totalCreditHour variables in each iteration:
subjectGradePoint = GradePoint * CreditHour;
totalSubjectGP += subjectGradePoint;
totalCreditHour += CreditHour;
Finally, after your loop calculate CGPA:
CGPA = totalSubjectGP / totalCreditHour;
Java mandates method variables to be initialized before use,
just initialize String value and it shall work fine. Please refer to below code extract.
String subjectName=null;
int subjectCreditHour=0;
String subjectGrade=null;
java variable must intialized before use
import java.util.Scanner;
/**
*
* #author jerem_000
*/
public class JavaQuiz1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String name;
int ID;
int tel;
String email;
int subjects;
String subjectName;
int subjectCreditHour=0;
int subjectMark;
String subjectGrade="";
double GradePoint=0;
double subjectGradePoint=0;
double CGPA;
double totalSubjectGP;
int totalCreditHour;
System.out.print("Please input student's name : ");
name = input.nextLine();
System.out.print("Please input student's ID : ");
ID = input.nextInt();
System.out.print("Please input student's telephone number : ");
tel = input.nextInt();
System.out.print("Please input student's email : ");
email = input.next();
System.out.print("Please input number of subjects : ");
subjects = input.nextInt();
for (int i = 1; i >= subjects ; i++) { //I'm having an issue with this loop
System.out.println("Subject " + i + " : Please input the following"); //I placed the variable i there in order to make the program print something like "Subject 1 , Subject 2, Subject 3 etc". Depending on the user's number of subjects input
System.out.print("Subject name : ");
subjectName = input.next();
System.out.print("Credit Hour : ");
subjectCreditHour = input.nextInt();
System.out.print("Mark : ");
subjectMark = input.nextInt();
if ( subjectMark >= 80 ) {
subjectGrade = "A";
GradePoint = 4.0;
} else if (subjectMark < 80) {
subjectGrade = "B+";
GradePoint = 3.5;
} else if (subjectMark < 70) {
subjectGrade = "B";
GradePoint = 3.0;
} else if (subjectMark < 65) {
subjectGrade = "C+";
GradePoint = 2.5;
} else if (subjectMark < 55) {
subjectGrade = "C";
GradePoint = 2.0;
} else if (subjectMark < 50) {
subjectGrade = "D";
GradePoint = 1.0;
} else {
subjectGrade = "F";
GradePoint = 0.0;
}
}
System.out.println("Grade = " + subjectGrade);
System.out.println("Subject Grade Point = " + (GradePoint * subjectCreditHour)); //I'm having a problem with the subjectGrade, GradePoint, and subjectCreditHour, it says variable might have not been initialized
System.out.println("Name : " + name);
System.out.println("ID : " + ID);
System.out.println("Tel : " + tel);
System.out.println("email : " + email);
System.out.print("Total subject Grade Points = " );
System.out.print("Total Credit Hours = " );
System.out.print("Cumulative Grade Point Average ="); //On this 3 system.out.prints, I can't seem to think of a way to read the Grade Point, Total Credit Hours, and CGPA, and add them all together
}
}