Why the class Remark is not inheriting the Average class value? - java

import java.util.Scanner;
class Average {
int math, programming, oop, total;
public void setGrade(int math, int programming, int oop) {
this.math = math;
this.programming = programming;
this.oop = oop;
this.total = (math + programming + oop) / 3;
}
public int getTotal() {
return total;
}
}
class Remark extends Average {
void remark() {
int totalMark = super.getTotal();
if(totalMark >= 75) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
}
}
class Course extends Average {
void decideCourse() {
int total = super.getTotal();
System.out.println("Average: " + total);
if(total >= 91 && total <= 100) {
System.out.print("Course Offered: \nBSE, BEED, BSAT");
}
else if(total >= 81 && total <= 90) {
System.out.print("Course Offered: \nBSIT, BSCS, BSBA");
}
else if(total >= 75 && total <= 80) {
System.out.print("Course Offered: \nBSITECH, DAT, BSHRM");
}
else if(total < 75) {
System.out.print("Average did!");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int math, programming, oop;
System.out.print("Enter Grade: ");
System.out.print("\nMath: ");
math = sc.nextInt();
System.out.print("Programming: ");
programming = sc.nextInt();
System.out.print("Object-Oriented Programming: ");
oop = sc.nextInt();
Course c1 = new Course();
Remark r1 = new Remark();
c1.setGrade(math, programming, oop);
r1.remark();
c1.decideCourse();
}
}
This problem is related to inheritance. A student need to be graded on the average marks.
In this code class Remark is not extending Average class, when i try to get the total from Average class, its not inheriting.. whats the error here... other parts are working fine

Each Remark (including r1) and each Course (including c1) will have its own copy of all of the fields you define in Average. It is not the case that there is one shared copy of Average; there is one for each instance of Average, and each instance of Remark and Course contains space for all of Average's fields.
No matter what values you enter, r1.remark() will always print "Fail" because you're setting the values in c1 and not r1. Though r1 will inherit the definition of getTotal from Average, you haven't set the values, so they'll all have the default value of 0 and consequently getTotal will return 0.
(Side note: Though it works from a technical standpoint, you might not see cases later where classes like Remark and Course extend a class like Average: You are representing that if some other part of your program needed an Average, you could pass in a Remark or a Course, and that doesn't make as much sense as if (for instance) you had Course, Assignment, and Exam all extend GradableItem. You'll see that principle referred to as the Liskov Substitution Principle.)

Related

Confusion about how to process lines in a text file as they are read

So I was given the following GradedActivity class:
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
if (s < 0)
score = 0.0;
else if (s > 100)
score = 100.0;
else
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} }
and I was tasked with generating a constructor that accepts values for points Obtaned and pointsTotal as arguments, initializes them, and sets the corresponding score (points obtained divided by points total), accessors and mutators for pointsobtained and total.
So here is what I came up with:
public class ProgrammingAssignment extends GradedActivity
{
public int pointsObtained;
public int pointsTotal;
public ProgrammingAssignment(int p, int t)
{
pointsObtained = p;
pointsTotal = t;
}
public int getPointsObtained()
{
return pointsObtained;
}
public int getPointsTotal()
{
return pointsTotal;
}
public double getScore()
{
return pointsObtained / pointsTotal;
}
public void setPointsObtained(int p)
{
pointsObtained = p;
}
public void setPointsTotal(int t)
{
pointsTotal = t;
}
}
Everything compiles without error, but getScore isn't computing obtained/total (it comes back 0) in my test class:
public class PADemo
{
public static void main(String[] args)
{
ProgrammingAssignment p1 = new ProgrammingAssignment(28,30);
GradedActivity p2 = new ProgrammingAssignment(0,30);
System.out.println (p1.getPointsObtained());
System.out.println (p1.getPointsTotal());
System.out.println (p1.getScore());
System.out.println (p1.getGrade());
System.out.println (p2.getScore());
System.out.println (p2.getGrade());
p1.setPointsObtained(25);
p1.setPointsTotal(40);
System.out.println (p1.getScore());
System.out.println (p1.getGrade() == 'F');
}
}
How do I obtain the score (points obtained/points total) with getScore()
Test class returns:
28
30
0.0
F
0.0
F
0.0
true
Cars waiting: [a A123TR, a Z23YTU, a R23EWQ, a ERW345, a B12GFT...
Does that look correct? Why would you have the "a " at the beginning? That is not part of the car license. The "a " and "d " need to be removed BEFORE you add the license to the garage or queue.
creates a stack for cars in a garage (Max of 7)
a queue for cars waiting (max of 5)
Your basic logic appears wrong (to me).
When you get an "a" you do one of two things:
if there are less than 7 cars in the garage you add the car to the garage.
If there are 7, then if then are less the 5 cars in the queue, you add the car to the "queue".
When you get a "d" you:
first remove the car from the "garagee",
then you check the "queue". If there are cars in the "queue" then you move the car from the "queue" to the "garage".
So the logic might be structure something like:
while (...)
{
...
String[] data = line.split(" ");
if (data[0].equals("a"))
processArrival( data[1] );
else if (data[0].equals("d"))
processDeparture( data[1] );
}
I used the String.split(...) method which was suggested in your last question because it is a better test then to test the whole String for a specific character and your two pieces of data are separated into the array ready for processing. The data will now be split into two pieces of data: a) function
b) license
I used separate methods because the code is easier to read and logic for each function is contained in individual methods.

Simple Discount

Studying for an exam and have a problem,I am a beginner.
Its a discount calculator.
Bag of coffee costs €3.75
10 bags or more 5% discount
20 bags or more 10% discount
What I have so far
import java.util.Scanner;
public class discount {
public static void main (String[] args){
//Scanner input; Keep this as one line. It is good practice
Scanner input = new Scanner(System.in);
double bag;
double discount;
double cost = 3.75;
//Input = new Scanner(System.ini); combined with line above.
System.out.println("Enter Numer of bag");
bag = input.nextDouble();
//If (bag ==>10&&<20) × .05 incorrect Java syntax
if(bag >= 10 && < 20) {
discount = 0.05;
}
else if(bag >= 20) {
discount = 0.10;
}
else {
discount = 0;
}
double finalPrice;
finalPrice = (cost * bag) * (1 - discount);
System.out.println("You ordered " + bag + " bags of coffee.");
System.out.println("Your dicount is " + discount + "%");
System.out.println("You total is: " + finalPrice);
}
}
if(bag >= 10 && < 20)
to
if(bag >= 10 && bag < 20)
An easy mistake for a beginner!
I kinda agree with the lecturer re the editor vs ide while learning the basics. You need to learn to read what the compiler tells you is wrong. And once you know the problem, I think you will agree, the syntax error message above gives a good indication of what is wrong.
I'm usually not in favor of doing assignments for Tom Sawyer students, but in this case I think there's educational opportunity for any beginner who learns to look at the problem differently.
This is a simple class, but it's a good idea to develop good habits if you want to be a programmer.
Pay a lot of attention to code formatting and readability. Think long and hard about names for classes, methods, and variables. You need fewer comments if the names are self-explanatory.
Learn and follow Java coding standards. That will help readability.
Forget about input and output and the user interface - get the functionality right first.
import java.util.LinkedHashMap;
import java.util.Map;
/**
* CoffeePriceCalculator
* User: mduffy
* Date: 7/22/2016
* Time: 7:46 AM
* #link http://stackoverflow.com/questions/38525213/simple-discount
*/
public class CoffeePriceCalculator {
// Is double a good way to represent money? What about units? Conversions?
public static final double DEFAULT_UNIT_PRICE = 3.75; // British pounds
private static final Map<Integer, Double> DISCOUNT_PERCENTAGE;
static {
DISCOUNT_PERCENTAGE = new LinkedHashMap<>();
DISCOUNT_PERCENTAGE.put(10, 0.05);
DISCOUNT_PERCENTAGE.put(20, 0.10);
}
public double calculatePrice(int numBags, double unitPrice) {
if (numBags < 0) throw new IllegalArgumentException("Number of bags must be positive");
if (unitPrice < 0.0) throw new IllegalArgumentException("Unit price must be positive");
double price = numBags*unitPrice;
price -= calculateDiscount(numBags, price);
return price;
}
public double calculatePrice(int numBags) {
return this.calculatePrice(numBags, DEFAULT_UNIT_PRICE);
}
public double calculateDiscount(int numBags, double price) {
if (numBags < 0) throw new IllegalArgumentException("Number of bags must be positive");
if (price < 0.0) throw new IllegalArgumentException("Total price must be positive");
double discount = 0.0;
for (int minBags : DISCOUNT_PERCENTAGE.keySet()) {
if (numBags >= minBags) {
discount = price*DISCOUNT_PERCENTAGE.get(minBags);
break;
}
}
return discount;
}
}
It's not too early to learn about JUnit and Test Driven Development.
import org.junit.Assert;
import org.junit.Test;
/**
* Junit test for CoffeePriceCalculator
* User: mduffy
* Date: 7/22/2016
* Time: 7:50 AM
* #link http://stackoverflow.com/questions/38525213/simple-discount
*/
public class CoffeePriceCalculatorTest {
public static final double TOLERANCE = 1.0e-3;
#Test
public void testCalculatePrice_NoDiscount() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = 5;
// exercise
double actual = coffeePriceCalculator.calculatePrice(numBags);
// assert
Assert.assertEquals(numBags * CoffeePriceCalculator.DEFAULT_UNIT_PRICE, actual, TOLERANCE);
}
#Test
public void testCalculatorPrice_LowDiscount() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = 15;
// exercise
double actual = coffeePriceCalculator.calculatePrice(numBags);
// assert
Assert.assertEquals(numBags * CoffeePriceCalculator.DEFAULT_UNIT_PRICE*0.95, actual, TOLERANCE);
}
#Test
public void testCalculatorPrice_HighDiscount() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = 25;
// exercise
double actual = coffeePriceCalculator.calculatePrice(numBags);
// assert
Assert.assertEquals(numBags * CoffeePriceCalculator.DEFAULT_UNIT_PRICE*0.90, actual, TOLERANCE);
}
#Test(expected = IllegalArgumentException.class)
public void testCalculatePrice_NegativeBags() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = -25;
// exercise
coffeePriceCalculator.calculatePrice(numBags);
}
}
Hopefully your exam is not coming up too soon, because you have a lot of syntax to review.
I don't really like giving straight up answers to homework questions, so I will fix up what you currently have, and perhaps that will point you in the right direction.
Import.java.util.scanner;
public class discount {
public static void main (String[] args){
//Scanner input; Keep this as one line. It is good practice
Scanner input = new Scanner(System.in);
//Float bag;
int bag;
Float discount;
Double cost = 3.75;
//Input = new Scanner(System.ini); combined with line above.
System.out.println("Enter Numer of bag");
bag = input.nextFloat();
//If (bag ==>10&&<20) × .05 incorrect Java syntax
//if(bag >= 10 && < 20) {
if(bag >= 10 && bag < 20) {
discount = 0.05;
}
else if(bag >= 20) {
discount = 0.10;
}
else {
//discount = 0;
discount = 0.0;
}
double finalPrice;
finalPrice = (cost * bag) * (1 - discount);
//System.out.println("You ordered " + bag + " bags of coffee.);
System.out.println("You ordered " + bag + " bags of coffee.");
System.out.println("Your dicount is " + discount + "%");
System.out.println("Your total is: " + finalPrice);
}
}
Remember to keep your code clean so you do not confuse yourself. Make sure you indent your code.
Think about what you are naming your variables, and do not be afraid to refactor them if you come up with something better. Using clear and logical naming will reduce the number of comments you will need to write.
And as I mentioned before, study up on your syntax. There were a lot of syntax errors in your code, which leads me to believe that maybe you are writing your code in notepad or from the command line? If so I would recommend using an IDE such as IntelliJ, NetBeans, or Eclipse. These will underline your syntax errors and point out mistakes that you may not notice straight away.

Where to add an Array?

I have this simple project due tomorrow and I'm almost done but the thing is that one of the requirements in class is for it to have an array, a scanner (which I have) and inheritance.
This is what I have so far:
import java.util.*;
import java.io.*;
public class TestScores
{
public static void main(String[] args)
{
System.out.println("Enter scores from a range of 0 to 100.");
System.out.println("");
Scanner kbReader = new Scanner(System.in);
int testscore = kbReader.nextInt();
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
I don't know how to incorporate the array and the inheritance.
What would be the subclass?
Well you could create a Grade Object lets say so you could now have an array of Grade Objects defined as:
Grade[10] grades = new Grade[10]; // 10 Grade Objects can be stored
Then i guess based on your code you could have subclasses of Grade so AGrade, BGrade etc.. and have them contain extra information.
Class Grade {
int mark;
public Grade(int mark){
this.mark = mark;
}
}
Class AGrade extends Grade {
String message = "wooo i got an A";
public AGrade(){
//access mark or message or what ever you want to add here
}
}
I'll leave the rest of the implementation up to you, but you will need to use super access if you want to access the mark in AGrade. It is not clear how much inheritance you have done but if you come from c++ Java does NOT support multiple inheritance.
I might be wrong in what ive said, but it is hard to tell exactly what you are looking for based on the above, i don't see a real need for subclasses here if you are only using a mark and printing out a char.
The example i give uses a message in each Class, so you can show the difference clearly between subclasses.

Answer returning 0

Total beginner in Java. My result keeps turning up as 0 where I want it to turn up as membercount * members (ie if there are 100 members and the weather = 1, the total should be 25). I can't seem to figure out where I'm going wrong. I figure I'm not properly having my program store the information entered by the user so the doubles keep reading as 0. Here is my code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package playgolf;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
* #author Alex
*/
public class PlayGolf {
public static void main(String[] args) {
golf stats = new golf();
stats.getData();
golf total = new golf();
total.display_data();
}
}
class golf {
private double members;
private double weather;
private double temp;
private double membercount;
public double total;
public void getData() {
Scanner input = new Scanner(System.in);
System.out.print("How many members are there?: ");
members = input.nextInt();
System.out.print("What is the weather like? (Enter 1 for sunny, 2 for overcast, 3 for rain): ");
weather = input.nextInt();
System.out.print("What is the temperature? (in Farenheight): ");
temp = input.nextInt();
if (weather == 1) {
membercount = .25;
if (weather == 2) {
membercount = .12;
if (weather == 3) {
membercount = .03;
}
}
}
if (temp < 32) {
membercount = 0;
System.out.println("No one will play today, it's too darn cold!");
}
total = (membercount * members);
}
public void display_data() {
System.out.println(" ");
System.out.println("This many members will play today: ");
System.out.println(total);
}
}
You create new object again, it should be:
public static void main(String[] args) {
golf stats = new golf();
stats.getData();
stats.display_data();
}
Bug 1
The code blocks related to your weather logic are messed up; the closing braces are in the wrong place.
Properly indented, your code looks like this:
if (weather == 1) {
membercount = .25;
if (weather == 2) {
membercount = .12;
if (weather == 3) {
membercount = .03;
}
}
}
Now you can probably already see the bug. If weather is 2, the weather == 2 condition will never be reached (weather cannot be 1 and 2 at the same time).
Corrected version:
if (weather == 1) {
membercount = .25;
}
else if (weather == 2) {
membercount = .12;
}
else if (weather == 3) {
membercount = .03;
}
Bug 2
Another bug is in the main method. You should call display_data() on the same object as getData(). This would work:
golf stats = new golf();
stats.getData();
stats.display_data();
Other problems & style issues
display_data is not idiomatic Java method name. Should be displayData.
Likewise, Java class names should start with uppercase letter. Golf, not golf. See e.g. this guide on Java naming conventions.
It's suspicious to use double to represent one of three possible values (weather). Use int, or better yet, an enum. Also for members it is a pretty odd choice of type.
Since your if conditions are nested, if weather != 1, the checks for weather == 2 and weather == 3 are never reached.
As a consequence, membercount is never set and takes the value of zero, yielding your zero result for total.
You should just have something like the following:
switch (weather) {
case 1:
membercount = .25;
break;
case 2:
membercount = .12;
break;
case 3:
membercount = .03;
break;
default:
// Do nothing or, better yet, produce an error
}
if (temp < 32) {
// ...
You could simply use a series of ifs, or an if-else chain. I'm using a switch because it's the safest choice in this case. This assumes that you change weather to be an int, which is actually preferable given your use of the variable. You should also esplicitly initialize the value of weather during declaration (or in the constructor, as you see fit):
private int weather = 0;
As pointed out by the other answers, you have a secondary bug in your listing: you should create only one object and have both calls on that, as follows:
golf stats = new golf();
stats.getData();
stats.display_data();
You are calling getData() on one instance (of golf) and calling display_data() on another one. The stats collects data, but the total does not. Try to call display_data() on stats instance / or call getData() on total instance / or use shared members (statics I mean).
golf stats = new golf();
stats.getData();
stats.display_data();
or
golf total = new golf();
total.getData();
total.display_data();

Java driver class, Runnable, and main method

I am to create a program in Java using multiple methods inside the driver class. Previously, we have only used the main method in such applications.
I know I am to use something like this:
public static void main(String[] args)
{
U4A4 u = new U4A4();
u.run();
}
to run the method public U4A4().
Yes, I know this is terribly basic, but I've been searching around all evening and I thought someone here might be able to put it in simple terms how exactly I should do this.
My compiler is getting mad when I try to put in public class U4A4 implements Runnable at the top of my code (it's right after my imports) and starts wanting me to make it abstract. I have no idea what that is.
So, where do I put implements Runnable and where do I use run()?
Thank you so much for bearing with me here.
Edit: This is what I've got so far. http://pastebin.com/J8jzzBvQ
You have implemented Runnable interface, but not overriden the run method of that interface. I have commented code where you will have to place your thread logic so the thread will work for you.
import java.util.Scanner;
public class U4A4 implements Runnable
{
private int count = 0;
private double accum = 0;
private int apr, min, months;
private double balance, profit;
public static void main(String[] args)
{
U4A4 u = new U4A4();
u.run();
}
public U4A4()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter credit card balance: ");
balance = in.nextDouble();
System.out.print("\n\nEnter minimum payment (as % of balance): ");
min = in.nextInt();
System.out.print("\n\nEnter annual percentage rate: ");
apr = in.nextInt();
profit = this.getMonths(balance);
System.out.println("\n\n\n# of months to pay off debt = " + count);
System.out.println("\nProfit for credit card company = " + profit + "\n");
}
public double getMonths(double bal)
{
double newBal, payment;
count++;
payment = bal * min;
if (payment < 20 && bal > 20)
{
newBal = bal * (1 + apr / 12 - 20);
accum += 20;
} else if (payment < 20 && bal < 20)
{
newBal = 0;
accum += bal;
} else
{
newBal = bal * (1 + apr / 12) - payment;
accum += payment;
}
if (newBal != 0) {
getMonths(newBal);
}
return accum;
}
public void run() {
// TODO Auto-generated method stub
// You have to override the run method and implement main login of your thread here.
}
}

Categories

Resources