Weird error on driver class - java

I'm writing a driver class for a piggy bank class that I created. The idea is that it is supposed to add different types of coins (user input) and then total the cents and display them until "X" is input by the user. I think I have the code right, but there is a weird issue where if I use the "countMoney" accessor into the code, it tells me that all of my variables in the driver class are uninitialized. If I remove it, there are no errors shown by Eclipse. I've printed my source and driver class below:
package piggy;
/**
* #author Kevin
*
*/
import java.util.Scanner;
import piggy.PiggyBank;
public class PiggyBankTester {
/**
* #param args
*/
public static void main(String[] args) {
String num = "str", num1;
int count = 0;
int money;
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
PiggyBank total = new PiggyBank();
System.out.println("Welcome to the Piggy Bank Tester");
System.out.println("What type of coin to add (Q, H, D or X to exit)?");
num1 = scan.nextLine();
num = num1.toUpperCase();
{
if (num.equals("X"))
System.out.println("Goodbye.");
else if (num != "X")
{
System.out.println("How many do you wish to add?");
count = scan.nextInt();
if (num.equals("Q"))
total.addQuarters(count);
else if (num.equals("H"))
total.addHalfDollars(count);
else if (num.equals("D"))
total.addDollars(count);
else if (num.equals("X"))
System.out.println("Goodbye.");
}
}
{
total.calculate();
money = total.countMoney();
System.out.println("The piggy bank now contains " + money + " cents.");
}
}
}

You don't need (String Q,D,H,X) .
Also you have declared this variables without give them any value just name.
A way you can do it is to change your if-else statements and set , for example if you want num to be equal to Q ---> if (num.equals("Q") ) <---

Related

why "Keyboard.readDouble()" doesn't work?

All I want it to do is read input typed by the user as double type, and then convert it to another number. I'm also aware the equation isn't complete, not worried about that right now, just want it to run. I don't understand what I have done wrong.
public class EuroShoe {
public static void main(String[] args) {
double
footLength,
euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
footLength = Keyboard.readDouble(); // line 25
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
If you are following a tutorial, please check on the imports that were mentioned. But to answer your question and make your program work here's an answer.
import java.util.Scanner
public class EuroShoe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i =
double footLength, euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
// The statement below calls the "scanner" object to get the user input of value "double"
footLength = scanner.nextDouble();
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
Make sure to put this statement above
import java.util.Scanner // imports the specific Scanner class under the 'util' namespace
or you can use this as well
import java.util.* // imports every class under the 'util' namespace
Hope this helps you with your problem and keep coding! :)
This worked:
package euroshoe;
import java.util.Scanner;
public class EuroShoe {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
double footLength = input.nextDouble();
double euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}

"class X is public, should be in X.java" with Ideone online compiler

I am a student very new to programming and have made a simple program in java to convert units.
I am on a mac using ideone compiler online. I am receiving this error
Main.java:7: error: class AssessmentOne is public, should be declared in a file named AssessmentOne.java
public class AssessmentOne{
^
1 error
Here is my code (this is for an assignment I am working on hence the name):
package assessmentOne.pkg1;
import java.util.Scanner;
// MY NAME Assessment One
public class AssessmentOne{
public static void main(String[] args)
{ int choice;
do
{ Scanner input = new Scanner(System.in);
System.out.println("1 = centimetre to inch, 2 = metres to feet, 3 = finish");
choice = Integer.parseInt(input.next());
if (choice == 1)
{
// converts centimetre to inch
System.out.println("centimetre to inch");
double centimetre;
double inch;
inch = 0;
centimetre = Double.parseDouble(input.next());
System.out.println("inch = centimetre * 0.3973");
}
else if (choice == 2)
{
// converts metre to feet
System.out.println("metre to feet");
double metre;
double feet;
feet = 0;
metre = Double.parseDouble(input.next());
System.out.println("feet = metre * 3.28");
}
else if (choice == 3)
{
// exits
break;
}
} while (choice != 3);
}
}
As it says on a new Java project on that site:
/* Name of the class has to be "Main" only if the class is public. */
Either:
Remove the public part:
class AssessmentOne{
Rename the class to Main:
public class Main{
Remove public in below line of code and it works straight away.
"public class AssessmentOne{"
Just remove the "public" from "public class AssessmentOne{". In other words, just write "class AssessmentOne {" and Voila! It would work.
I had the same problem and removing the "public" worked. Here is the link of a code that had the same problem. Click to see
package assessmentOne.pkg1;
import java.util.Scanner;
// MY NAME Assessment One
class AssessmentOne{
public static void main(String[] args)
{ int choice;
do
{ Scanner input = new Scanner(System.in);
System.out.println("1 = centimetre to inch, 2 = metres to feet, 3 = finish");
choice = Integer.parseInt(input.next());
if (choice == 1)
{
// converts centimetre to inch
System.out.println("centimetre to inch");
double centimetre;
double inch;
inch = 0;
centimetre = Double.parseDouble(input.next());
System.out.println("inch = centimetre * 0.3973");
}
else if (choice == 2)
{
// converts metre to feet
System.out.println("metre to feet");
double metre;
double feet;
feet = 0;
metre = Double.parseDouble(input.next());
System.out.println("feet = metre * 3.28");
}
else if (choice == 3)
{
// exits
break;
}
} while (choice != 3);
}
}
I'm not sure but this error usually appears when the name of the java file is differente than the class name. When you declare your class as public the java file that contains it must have the same name than .java.
Example
public class Example {}
Example.java

Displaying a function calculation

I'm encountering an issue on a program I'm compiling. i got to display the actual calculation on function 2.The main program is called display11 and I'm calling the functions on the other class. can't figure it out whats wrong that is not displaying the loop. thanks a lot
import java.util.Scanner;
/**
*
* #author ec1302696
*/
public class Functions
{
private int n;
public void string_function(String name)
{
int optionChosen;
String fname;
String sname;
Scanner keyboard = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
Functions fun = new Functions();
System.out.println("Please enter full name");
fname = sc.nextLine(); //accept first name entered by user
//****enter as a comment for now fun.first(fname);
fun.createname(fname);// this create name
//display this is option 1,administrator name admin
//ask for full name for generating username
//call createname passing the username
}
public void number_function(String admin)
{
{
int n, c, fact = 1;
System.out.println("Enter a number to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
// return fact;
//this is option 2 ,administrator name admin
//read the factorial
//calcualte the fatorial
// print it
}
}
public void createname(String username)
{
String fname = fname.substring(0,1);
System.out.println("The usernameis " + fname);
//string calcualte the string function to find the first letter ,and second name.
//concatenate and print it.
}
}
import java.util.Scanner;
/**
*
* #author ec1302696
*/
public class Display11 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Functions fun = new Functions();// this create teh functions
int optionChosen;
String admin;
Scanner keyboard = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
admin = keyboard.nextLine();
{
System.out.println("Welcome please select option from menu below");
}
System.out.println("OPTION 1 – USERNAME");
System.out.println("OPTION 2 - CALCULATE THE FACTORIAL");
System.out.println("OPTION 3 - EXIT");
optionChosen = keyboard.nextInt();
if (optionChosen == 1)
{
fun.string_function(admin);
}
else if (optionChosen == 2) {
{
fun.number_function(admin);
}
}
else if (optionChosen == 3)
{
}
}
}
If you need to show the calculation of the factorial, change the calculation loop to something like this:
StringBuilder result = new StringBuilder("Factorial of ").append(n).append(" is ");
for ( c = n ; c >0 ; c-- )
{
result.append(c);
if(c>1)
{
result.append(" * ");
}
fact = fact*c;
}
result.append(" = ").append(fact);
System.out.println(result);

Inheritance Error in java

This is super class of all,Employee class.
import java.util.Scanner;
import java.util.Calendar;
import java.util.*;
class Employee {
Scanner in = new Scanner(System.in);
Calendar cal = Calendar.getInstance();
String name;
String number;
int month;
int week;
double pay;
void load() {
System.out.println("Enter name of employee");
name = in.nextLine();
System.out.println("Enter social security number");
number = in.nextLine();
System.out.println("Enter employee's birthday month(1-12)");
month = in.nextInt();
System.out.println("Enter employee's birthday week(1-4)");
week = in.nextInt();
}
public String toString() {
return "employee : " + name + " social security number : " + number
+ " paycheck : $" + pay;
}
void getBonus() {
int mont = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
if (month == mont + 1 && week == (day / 7) + 1)
pay = pay + 100;
}
}
This is subclass of employee .
import java.util.Scanner;
class Hourly extends Employee {
Scanner in = new Scanner(System.in);
double pay;
int hpay;
int hours;
void load() {
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
double getEarnings() {
if (hours > 40)
pay = 1.5 * (hours - 40) * hpay + hpay * 40;
else
pay = hpay * hours;
return pay;
}
}
There are 2 more subclasses like these and finally i have test file.
import java.util.Scanner;
class driver {
public static void main(String args[]) {
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out
.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
if (b == 1) {
Hourly h = new Hourly();
h.super.load();// error cannot find symbol h
h.load();
h.getEarnings();
}
if (b == 2) {
Salaried s = new Salaried();
s.load();
s.getEarnings();
}
if (b == 3) {
Salariedpluscommision sp = new Salariedpluscommision();
sp.super();// error that super should be in first line but then
// where can i define sp
sp.super.load();// cannot find symbol sp
sp.load();
sp.getEarnings();
}
}
}
}
I have got 3 errors in these codes and as i am beginner i don't know how can i solve these errors.
My program takes the employee's details from user and calculate paycheck of that employee.
Also,I am confused in how can i print all employee's paychecks at last after user have completed giving input of all employee's details.Can i do these with an array ?
But first,i have to remove these errors and also suggest my which topics are weak which i should focus more.
Thank you in advance
You appear to be a bit confused about the keyword super.
In the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.super();//error that super should be in first line but then where can i define sp
sp.super.load();//cannot find symbol sp
sp.load();
sp.getEarnings();
the compiler is telling you that super cannot be used where you're using it.
Most likely you just don't need it at all in the driver code and the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.load();
sp.getEarnings();
will do what you thought you needed these calls for.
Similarly, in the earlier code, you can likely just delete the line
h.super.load();// error cannot find symbol h
As it's coded however, you might need to call some superclass methods from your subclasses, which is what the keyword is for.
In Hourly and likely the other subclasses, you probably want to call the Employee load method within the subclass load method:
void load(){
super.load();
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
which appears to be what you were trying for with some of the non-compiling code in driver.
Several suggestions:
Make Employee an abstract class and add public abstract getEarnings(); method
Simplify your Driver routine to use switch / case rather than multiple if statements
Create an ArrayList to collect a list of all employees
Use the "type" of employee to create the right kind ... use the same variable name though
After creating the "right kind" of employee, load it and get the earnings
.... (print out the earnings?
Just create objects .. don't use "super
Consider the following for Driver:
import java.util.ArrayList;
import java.util.Scanner;
class driver {
public static void main(String args[]) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee emp;
double earnings;
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
emp = null;
switch (b) {
case 1:
emp = new Hourly();
break;
case 2:
emp = new Salaried();
break;
case 3:
emp = new Salariedpluscommision();
break;
default:
System.out.println("You entered an invalid employee type.");
break;
}
if (emp != null) {
emp.load();
earnings = emp.getEarnings();
employees.add(emp);
System.out.println("Earnings are: " + earnings + "for " + emp.getName());
}

Keep getting error of java.lang.nullexception: null

The code im working on is intended to accept an input from the user but whenever i run the program, it keeps telling me that there is an error, the java.land.nullexception: null. I dont know what to do!
import java.util.Scanner;
public class HamzasGrocery
{
// instance variables - replace the example below with your own
private Scanner in;
/**
* Constructor for objects of class HamzasGrocery
*/
public HamzasGrocery()
{
Scanner in = new Scanner(System.in);
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void sampleMethod()
{
double choice1;
double choice2;
double choice3;
double choice4;
double choice5;
double total;
System.out.print("Enter item #1: ");
System.out.println();
choice1 = in.nextDouble();
System.out.print("Enter item #2: ");
choice2 = in.nextDouble();
System.out.println();
System.out.print("Enter item #3: ");
choice3 = in.nextDouble();
System.out.println();
System.out.print("Enter item #4: ");
choice4 = in.nextDouble();
System.out.println();
System.out.print("Enter item #5: ");
choice5 = in.nextDouble();
System.out.println();
System.out.printf("%-10s", "Item #'s");
System.out.printf("%-10s", "Cost:");
System.out.printf("%-10s", "Total:");
}
}
Get rid of the Scanner in the "Scanner in = new Scanner.." code in the constructor.
By doing the declaration the way it is right now, you're saying that the in belong to the local scope and thus ignores the instance variable in.
So the constructor should be:
public HamzasGrocery()
{
in = new Scanner(System.in);
}
In your constructor, you are initializing a new Scanner, not your instance variable Scanner. try this:
public HamzasGrocery()
{
in = new Scanner(System.in);
}

Categories

Resources