I'm completely brand new to programming and Java so excuse any stupid mistakes and really awful code (I have no clue how to order/format). I've been given a task to make an inventory of videos which has three functions: list, rent and check. I have an ArrayList which holds the current inventory of videos available. Under the check function I want to be able to convert the returndate string into a Date and then compare this to today's date. If the returndate and today's date are equal I want to return a message saying: "Video is due today" and if the returndate has passed (is earlier than today's date) I want to return a message saying "Video is overdue".
I've been researching how to convert strings into dates and vice versa and have been trying all day to use this and more to try and make it work but I just can't seem to get it to work. I know there are many similar questions like this that have been asked and answered but I've tried following them and it's not working. Any help would be really appreciated. As I said before I'm a total newbie so excuse any stupidity.
Whole program code:
import java.text.DateFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;
class InventoryRow {
private String name;
private String type;
private Character availability;
private String returndate;
public InventoryRow(String name, String type, Character availability, String returndate) {
this.name = name;
this.type = type;
this.availability = availability;
this.returndate = returndate;
}
public String getReturndate() {
return returndate;
}
public void setReturndate(String returndate) {
this.returndate = returndate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Character getAvailability() {
return availability;
}
public void setAvailability(Character availability) {
this.availability = availability;
}
public String toString() {
return name + " " + type + " " + availability + " " + returndate;
}
}
public class InventorySort {
public static void main(String[] args) throws ParseException {
List<InventoryRow> videos = new ArrayList<InventoryRow>();
videos.add(new InventoryRow("Casablanca", "Old", 'Y', null));
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N', "2015-07-30"));
videos.add(new InventoryRow("2012", "Regular", 'Y', null));
videos.add(new InventoryRow("Ant-Man", "New", 'Y', null));
LocalDate dateReturn = LocalDate.now().plusDays(3);
LocalDate dateToday = LocalDate.now();
Scanner input = new Scanner(System.in);
// Output the prompt
System.out.println("Do you want to list (l), rent (r) or check (c)?");
// Wait for the user to enter a line of text
String line = input.nextLine();
// List, rent and check functions
// List function
if (line.equals("l")) {
// //////////////////////////// Sort function
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
// /////////////////////////// Rent function
} else if (line.equals("r")) {
System.out.println("Which video would you like to rent?");
String line2 = input.nextLine();
// /////////////////////////// Search through ArrayList
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line2.equals(ir.getName()) && ir.getAvailability() == 'Y') {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video available to rent! Would you like to rent this video?");
String line3 = input.nextLine();
if (line3.equals("Yes")) {
System.out.println("You have rented this video until " + dateReturn + ".");
for (InventoryRow ir : videos) {
if (ir != null && line2.equals(ir.getName())) {
ir.setAvailability('N');
ir.setReturndate(dateReturn.toString());
// //////////////// Just to test if this works
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
}
} else {
System.out.println("You have not rented this video.");
}
} else {
System.out.println("Video unavailable to rent.");
}
// /////////////////////////// Check function
} else if (line.equals("c")) {
System.out.println("Which video would you like to check is in the inventory?");
String line4 = input.nextLine();
// /////////////////////////// Search through ArrayList
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line4.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");
for (InventoryRow ir : videos) {
LocalDate returnDate = LocalDate.parse(ir.getReturndate());
if (line4.equals(ir.getName()) && ir.getAvailability() == 'N' && returnDate.isEqual(dateToday)) {
System.out.println("Video due for return today.");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N'
&& returnDate.isBefore(dateToday)) {
System.out.println("Video is overdue!");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N') {
System.out.println("Video is due for return on: " + ir.getReturndate());
}
}
} else {
System.out.println("Video not found. Please see the inventory below.");
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
// /////////////////////////// If anything else is entered
} else {
System.out.println("The only options are to list (l), rent (r) or check (c).");
}
}
}
This is the bit that isn't working and I don't know why:
if (foundIt) {
System.out.println("Video found!");
for (InventoryRow ir : videos) {
LocalDate returnDate = LocalDate.parse(ir.getReturndate());
if (line4.equals(ir.getName()) && ir.getAvailability() == 'N' && returnDate.isEqual(dateToday)) {
System.out.println("Video due for return today.");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N'
&& returnDate.isBefore(dateToday)) {
System.out.println("Video is overdue!");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N') {
System.out.println("Video is due for return on: " + ir.getReturndate());
}
}
This is the error message I get:
Exception in thread "main" java.lang.NullPointerException: text
at java.util.Objects.requireNonNull(Objects.java:228)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1846)
at java.time.LocalDate.parse(LocalDate.java:400)
at java.time.LocalDate.parse(LocalDate.java:385)
at InventorySort.main(InventorySort.java:141)
From your example:
// Gets today's date
Date todayDate = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
You have return date in string format as below:
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
"30/07/2015"));
Now the difference between current day and return date:
Date todayDate = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
String currDateStr = dateFormat.format(todayDate);
String returnDateStr = "01/08/2015";
Date returnDate = null;
try {
returnDate = dateFormat.parse(returnDateStr);
todayDate = dateFormat.parse(currDateStr);
}
catch (ParseException e) {
e.printStackTrace();
}
long diffInDays = (todayDate.getTime() - returnDate.getTime()) / (24 * 60 * 60 * 1000);
if (diffInDays == 0) {
System.out.println("Video is due today!");
}
else if (diffInDays > 0) {
System.out.println("Video is overdue :(");
}
else {
System.out.println("Video returned in advance :) ");
}
One thing you can do is instead of trying to covert "dates" is to convert the strings that represent the dates to numbers. The way you do this is by parsing a String to an Integer in this case. For example:
class Example {
public static void main(String[] args) {
String Date = "07/30/2015";
String[] DatesTxt = Date.split("/");
int[] DatesInt = new int[3];
for (int i = 0; i < DatesTxt.length; i++) {
DatesInt[i] = Integer.parseInt(DatesTxt[i]);
}
if (DatesInt[1] < 31) {
System.out.println("And look am comparing dates!");
}
}
}
I hope this helped :).
Related
When running the below method, I do not get anything back. Always getting terminated without any results. Could someone tell me why I am not getting any results back?
I hava adjusted according to the comments but havent worked. I have add the main method below;
public class ModuleGrader {
final int examID = 123;
String excellent =null;
String good=null;
String satisfactory=null;
String compensatableFail=null;
String outrightFail=null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark>=70 && mark<=100)
{
result = excellent;
System.out.println(" ");
}
else if (mark>=60 && mark<=69)
{
result = good;
}
else if (mark>=50 && mark<=59)
{
result = satisfactory;
}
else if (mark>=40 && mark<=49)
{
result = compensatableFail;
}
else if (mark>=0 && mark<=39) {
result = outrightFail;
}
else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
So I have add my invoking main method;
the method to call maybe the problem?
public static void main(String[] args) {
ModuleGrader mg=new ModuleGrader();
mg.gradeModule(100);
mg.gradeModule(66);}
You have assigned no values to String excellent;, String good;, so it fails because those values have not been initialized to anything when you call them.
How would you know that it is not working? You have no output of the final result to the console. I added System.out.println() to correct that.
You can't reference something which is not static from something which is static. Change public class ModuleGrader to public static class ModuleGrader.
Final Working Code
public class Main {
public static void main(String[] args) {
ModuleGrader mg=new ModuleGrader();
System.out.println(mg.gradeModule(100));
System.out.println(mg.gradeModule(66));
}
public static class ModuleGrader {
final int examID = 123;
String excellent = null;
String good = null;
String satisfactory = null;
String compensatableFail = null;
String outrightFail = null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark >= 70 && mark <= 100) {
result = excellent;
System.out.println(" ");
} else if (mark >= 60 && mark <= 69) {
result = good;
} else if (mark >= 50 && mark <= 59) {
result = satisfactory;
} else if (mark >= 40 && mark <= 49) {
result = compensatableFail;
} else if (mark >= 0 && mark <= 39) {
result = outrightFail;
} else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
}
}
You need to put quotes around the strings you want to assign.
result = excellent; should be result = "excellent"; and soforth for all your assignments to return
public class ModuleGrader {
final int examID = 123;
//String excellent=null;
//String good=null;
//String satisfactory=null;
//String compensatableFail=null;
//String outrightFail=null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark>=70 && mark<=100)
{
result = "excellent";
System.out.println(" ");
}
else if (mark>=60 && mark<=69)
{
result = "good";
}
else if (mark>=50 && mark<=59)
{
result = "satisfactory";
}
else if (mark>=40 && mark<=49)
{
result = "compensatableFail";
}
else if (mark>=0 && mark<=39) {
result = "outrightFail";
}
else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
Full Disclosure: This was an assignment, it has been marked already, but I want to understand why I'm getting this error.
I'm having some issues understanding why junit.framework.AssertionFailedError is being thrown. Normally when errors occur I could at least look at the stack trace and see what is happening. In this case, the output console shows this:
Testcase: testIsCorrectMCQ(mr_3.myTester): FAILED
null
junit.framework.AssertionFailedError
at mr_3.MyTester.testIsCorrectMCQ(Assign03Tester.java:207)
testIsCorrectMCQ(mr_3.MyTester): FAILED
In the test result tab in NetBeans, copying the stack trace gives me:
junit.framework.AssertionFailedError
at mr_3.myTester.testIsCorrectMCQ(myTester.java:207)
In the tester file, I have this:
#Test
public void testIsCorrectMCQ() {
System.out.println("isCorrect of MCQ");
MCQuestion instance = new MCQuestion(1,"Capital city of Canada is", 'A',
"Ottawa", "Vancouver", "New York", "Toronto");
assertFalse(instance.isCorrect("B"));
assertTrue(instance.isCorrect("A")); // line 207
}
My isCorrect method is this:
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
Any help in understanding what is happening is greatly appreciated.
Edit 1 : My MCQuestion source code
public class MCQuestion extends Question {
private char answer;
private String[] options;
public MCQuestion() {
super();
questionType = QuestionType.MULTIPLE_CHOICE;
}
public MCQuestion(int id, String text, char answer, String... options) {
super(id, text);
setOptions(options);
setAnswer(answer);
questionType = QuestionType.MULTIPLE_CHOICE;
}
public String[] getOptions() {
String[] getOptions = new String[this.options.length];
System.arraycopy(this.options, 0, getOptions, 0, this.options.length);
return getOptions;
}
public void setOptions(String... options) {
if (options.length > 0) {
this.options = new String[options.length];
for (int i = 0; i < options.length; i++) {
if (options[i].isEmpty())
throw new IllegalArgumentException("You have nothing in this option");
else
this.options[i] = options[i];
}
}
else throw new IllegalArgumentException("You have no options set");
}
public char getAnswer() {
return this.answer;
}
public void setAnswer(char ans) {
ans = Character.toLowerCase(ans);
int index = ans - 97;
if (Character.isLetter(ans) && index >= 0 && index < this.options.length)
this.answer = ans;
else throw new IllegalArgumentException(ans + " is not a valid answer option");
}
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
#Override
public String toString() {
String option = "";
if (this.options.length == 0)
option = "No options added, yet!";
else {
char index = 'a';
for (String e: options)
option += index + ") " + e + "\n";
}
return (super.toString() + "\n" + option);
}
}
You execute ans = Character.toLowerCase(ans); for whatever reason in your setAnswer() method before saving it in this.answer. This means that (userGuess.charAt(0) == this.getAnswer()) will return false when you provide the answer in upper case, but compare it with the stored lower case character.
Depending on if you want case insensitive answers or not, you should add or remove the Character.toLowerCase() call to your isCorrect() method as well.
I successfully made a linked list, but now I am having trouble processing it. What methods do I need to add to my FoodList class to be able to process my objects? For example, I need to have the user be able to choose to manually add food objects together so I can print a meal. Also, I can't use any collections classes from the java API. It all must be custom.
public static void main(String[] args) {
FoodList list = new FoodList();
boolean keepGoing = true;
int scanResultInt;
try
{
//I/O stream
FileReader fr = new FileReader("foodlist.txt");
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
Food hold = new Food();
while(scan.hasNext()){
list.add(hold = new Food());
String str = scan.next();
//str = scan.next();
hold.setName(str);
str = scan.next();
hold.setGroup(str);
int cal = scan.nextInt();
hold.setNumCal(cal);
double percent = scan.nextDouble();
hold.setPercentDV(percent);
list.add(hold);
}
//System.out.println("" + list.toString());
br.close(); //close I/O stream
}
catch(IOException e){
System.err.println("I/O EXCEPTION: " + e.getMessage());
}
Scanner scan2 = new Scanner(System.in);
do {
System.out.println("---------------------------------------------------------");
System.out.println(" Welcome to the Parkland Meal Selector" );
System.out.println("---------------------------------------------------------");
System.out.println("Enter the number of the menu option you would like to select:");
System.out.println(" 1) List food database");
System.out.println(" 2) Create meal by manual selection");
System.out.println(" 3) Create meal by random selection");
System.out.println(" 4) Remove foods high in calories");
System.out.println(" 5) Exit");
scanResultInt = scan2.nextInt();
switch(scanResultInt) {
case 1: {
System.out.println("" + list.toString());
break;
}
case 2: {
System.out.println("Create-A-Meal Menu\n");
System.out.println("Enter the name of a food you would like to add:\n");
String foodWanted = scan2.next();
/*while( != null){
if(foodWanted.equals());
}*/
/*Food tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;*/
}
case 3: {
System.out.println("Create meal by random selection: \n");
break;
}
case 4: {
System.out.println("Remove Food High In Calories: \n");
break;
}
case 5: {
keepGoing = false;
break;
}
}
}
while(keepGoing);
}
Here is my Linked List:
public class FoodList {
// Class fields
private FoodNode head;
private int listCount;
// Private inner class
private class FoodNode
{
public Food f;
public FoodNode next;
public FoodNode(Food f)
{
this.f = f;
this.next = null;
}
}
// Constructor for LinkedList
public FoodList()
{
// Initialize start of the list
head = null;
listCount = 0;
}
// Add method (adds a reservation to the linked list)
public void add(Food f)
{
// Create a new ReservationNode
FoodNode node = new FoodNode(f);
// If this is the first node
if( head == null )
head = node;
else
{
FoodNode tmp = head;
while(tmp.next != null)
tmp = tmp.next;
tmp.next = node;
}
listCount++
}
/*public boolean hasThatFood(String food){
boolean haveThat = false;
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
if (food == f.getName());
haveThat = true;
}
return haveThat;
}*/
/*public boolean hasNext(){
boolean hasNext = false;
if(head != null) {
hasNext = true;
return hasNext;
}
}*/
#Override
public String toString() {
String result = "My Foods:" + '\n';
// Loop through all the reservation nodes
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;
}
}
And my Food class
public class Food {
private String name;
private String group;
private int numCal;
private double percentDV;
public Food() {//String name, String group, int numCal, double percentDV
/*this.name = name;
this.group = group;
this.numCal = numCal;
this.percentDV = percentDV;*/
name = "";
group = "";
numCal = 0;
percentDV = 0.0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getNumCal() {
return numCal;
}
public void setNumCal(int numCal) {
this.numCal = numCal;
}
public double getPercentDV() {
return percentDV;
}
public void setPercentDV(double percentDV) {
this.percentDV = percentDV;
}
#Override
public String toString() {
return "Food{" +
"name: '" + name + '\'' +
", Food Group: '" + group + '\'' +
", Calories: " + numCal +
", Daily Percent: " + percentDV +
'}';
}
}
I know this is spaghetti code, but this is my last resort. Any help would be appriciated!
To operate on the objects you have to write your custom Iterator. I guess here is nothing criminal to open LinkedList source and look how it works.
Something like this, You can find many resource online,
https://crunchify.com/how-to-implement-a-linkedlist-class-from-scratch-in-java/
Here is one.
public Object getElement(int index)
{
if (index < 0)
return null;
Node Current = null;
if (head != null) {
Current = head.getNext();
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return null;
Current = Current.getNext();
}
return Current.getData();
}
return Current;
}
You have implemented some complicated classes. Inner logic of its is not very clear like your issue. So almost any answer will not cover your needs.
If I would you I would try recommend the logic using java core tools (without implementing classes, that implemented in best way LinkedList, ArrayList...). Logic should be converted into some structural solution. For example:
enter point creates and calls your stream service to handle provided input stream;
stream handler should manipulate builder;
builder result have to be collected into composite;
and so on...
If you provide your logic in more structural way you would ask more clear question pointing the issue. Also I believe your question will disappear after this preparation.
Also I would recommend you to get familiar with next GoF patterns: builder, factory method, composite, strategy.
I'm having a problem calling a method and then trapping its return.
I need it to update the result so the next time round the loop it will see it and return a different message.
public class Patient {
private char patientStatus;
public boolean admit() {
if (patientStatus != 'S')
return false;
else
patientStatus = 'A';
return true;
}
This section is in the main() method
do {
Patient temp = null;
System.out.print("Enter selection: ");
menuSelect = sc.nextLine();
// validation
if (menuSelect.length() != 1) {
System.out.println("You must enter a single character");
} else {
menuAnswer = menuSelect.charAt(0);
switch (menuAnswer) {
case 'A':
case 'a':
// patient number
System.out.print("Enter patient number: ");
patNumber = sc.nextLine();
// search for patient number
for (int i = 0; i < pat.length && temp == null; i++) {
if (pat[i].getPatientNo().equals(patNumber)) {
temp = pat[i];
}
}
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean patStatus = temp.admit();
if (patStatus == false) {
System.out.println("Admitted");
} else if (patStatus == true) {
System.out.println("Already admitted");
}
}
}
}
} while (menuAnswer != 'x' && menuAnswer != 'X');
System.out.println("Exiting menu");
I don't know how to update the patStatus so the next time in the menu if you select 'A' and the same patient number it returns "Already admitted".
Let me know if there's enough code to understand what's happening.
Your Patient has the atribute for patientStatus but its value is never saved. Your admit() method needs to set the value for it.
Currently, your code only returns the value but does not save it.
Try this:
public class Patient {
private char patientStatus;
/** "Getter" method for patientStatus
*/
public char getPatientStatus(){
return patientStatus;
}
/** "Admits" the new patient, changing its patientStatus
* #return "true" if patient is admitted; "false" if patient was already admitted.
*/
public boolean admit() {
if (patientStatus != 'A')
patientStatus = 'A'; //set the value to Admitted
return true;
else
return false;
}
}
Then, in your loop, test the value for the admit() call:
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean admitted = temp.admit(); // try to admit the patient
if (admitted) {
System.out.println("Admitted");
} else { //You don't need another if here
System.out.println("Already admitted");
}
}
Since admitted is of type boolean, you don't need to use the == operator, as the if statement uses a boolean value as argument.
You don't need a second if statement after the else either, since boolean can only have two values, if it is not true, then it can only be false
/* You have to re-factor the code on these lines.
Maintain Patients class which holds admitted patients.*/
public class Patients{
private ConcurrentHashMap<Integer, Patient> allPatients = new ConcurrentHashMap();
private HashSet<Integer) admittedPatients = new HashSet();
public Patients(){
}
public void add(Patient p){
allPatients.put(p.getPatientId(),p);
}
public Patient removePatient(int patientId){
dischargePatients.remove(patientId);
return allPatients.remove(patientId);
}
public Patient getPatient(int patientId){
return allPatients.get(patientId);
}
public void admitPatient(int patientId){
admittedPatients.add(patientId);
}
public boolean dischargePatient(int patientId){
return admittedPatients.remove(patientId);
}
public boolean isAdmittedPatient(int patientId){
return admittedPatients.contains(patentId);
}
}
From `Patient.java` class, you can admit & discharge patient.
If getPatient() is null implies patient is not present in list.
Once he is present, isAdmittedPatient returns whether
he is admitted or not.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to create a method so I can set the "tuitionFees" and "scholarships" as a double for the profile of the user of the program. I'm unsure if I'm even setting this up right.
import java.util.Scanner;
/**
StudentInvoice.java
Defines StudentInvoice objects
#author: Evan Fravert
*/
public class StudentInvoice {
// declare instance variables here
// constructor
// methods
// toString method (for String output)
private String studentName;
private String studentNumber;
private double tuitionFees;
private double scholarships;
public String toString() {
String output = "Name: " + studentName + "\n";
output += "Student ID Number: " + studentNumber + "\n";
output += "Tuition & Fees: " + tuitionFees + "\n";
output += "Scholarship: " + scholarships + "\n";
return output;
}
public StudentInvoice(String name, String number, double fees, double scholarship){
studentName = name;
studentNumber = number;
tuitionFees = fees;
scholarships = scholarship;
}
public boolean setStudentName(String name){
if(name.length() == 0)
{
return false;
}
else
{
studentName = name;
return true;
}
}
public boolean setStudentNumber(String number){
if(number.length() == 0)
{
return false;
}
else
{
studentNumber = number;
return true;
}
public boolean setTuitionFees(double fees){
if(fees < 0.0) {
return false;
}
else {
tuitionFees = fees;
return true;
}
}
public boolean setScholarships (double scholarship){
if(scholarship < 0.0) {
return false;
}
else {
Scholarships = scholarship;
return true;
}
}
}
}
My class with the interactions:
public class StudentInvoiceApp {
public static void main (String[] args) {
StudentInvoice Evan = new StudentInvoice("Evan Fravert");
Evan.setName("Evan Fravert");
Evan.setNumber(01234);
Evan.setTuitionFees(0.00);
Evan.setScholarship(0.00);
System.out.print(Evan);
}
}
Upon trying to edit your post, I discovered you had a missing brace after setStudentNumber. The corrected code with proper formatting is below. In any programming language, formatting your code is important to understanding its meaning. People write entire books on how to format code, and for good reason. With good formatting, you likely would have noticed the missing brace.
Searching for "How to format Java code" yields several useful conventions, including documents from Oracle about how they format their Java code. When in doubt, most IDE's provide shortcuts to format code as well. In Eclipse, it's Ctrl+Shift+F, and in NetBeans, it's Alt+Shift+F.
import java.util.Scanner;
/**
* StudentInvoice.java Defines StudentInvoice objects
*
* #author: Evan Fravert
*/
public class StudentInvoice {
// declare instance variables here
// constructor
// methods
// toString method (for String output)
private String studentName;
private String studentNumber;
private double tuitionFees;
private double scholarships;
public String toString() {
String output = "Name: " + studentName + "\n";
output += "Student ID Number: " + studentNumber + "\n";
output += "Tuition & Fees: " + tuitionFees + "\n";
output += "Scholarship: " + scholarships + "\n";
return output;
}
public StudentInvoice(String name, String number, double fees,
double scholarship) {
studentName = name;
studentNumber = number;
tuitionFees = fees;
scholarships = scholarship;
}
public boolean setStudentName(String name) {
if (name.length() == 0) {
return false;
} else {
studentName = name;
return true;
}
}
public boolean setStudentNumber(String number) {
if (number.length() == 0) {
return false;
} else {
studentNumber = number;
return true;
}
}
public boolean setTuitionFees(double fees) {
if (fees < 0.0) {
return false;
} else {
tuitionFees = fees;
return true;
}
}
public boolean setScholarships(double scholarship) {
if (scholarship < 0.0) {
return false;
} else {
scholarships = scholarship;
return true;
}
}
}
change your setStudentNumber method to this
public boolean setStudentNumber(String number){
if(number.length() == 0)
{
return false;
}
else
{
studentNumber = number;
return true;
}
}
you were missing an closing brace for else