Problems with instantiating in Java - java

When running below program, I cannot reach the end of the main function...
I am new to Java, and cannot find its defects. I need your help. Thanks.
import java.util.*;
class Schedule {
public String day;
private int startTime, endTime;
public Schedule(String input_day, int input_start, int input_end) {
day = input_day;
startTime = input_start;
endTime = input_end;
}
/* clashWith: to check whether this schedule clash with a Schedule called otherSchedule
* PRE-Condition : input must be of Schedule type
* POST-Condition : return true if two Schedule clash, return false if not.
*/
public boolean clashWith(Schedule otherSchedule) {
if(this.day != otherSchedule.day || this.endTime <= otherSchedule.startTime || this.startTime >= otherSchedule.endTime)
return false;
return true;
}
}
class Module {
String code;
Schedule lecture, tutorial, lab;
public Module(String input_code, Schedule input_lecture, Schedule input_tutorial, Schedule input_lab) {
code = input_code;
lecture = input_lecture;
tutorial = input_tutorial;
lab = input_lab;
}
/* count: to count number of classes(lecture, tutorial, and lab of only this Module) on day.
* For example: when day = "Monday", lecture is on Monday, tutorial is on Monday
* but lab is on Tuesday, then return 2. (lecture and tutorial are on Monday).
* PRE-Condition :
* POST-Condition :
*/
public int count(String day) {
int num = 0;
if(lecture.day == day)
num++;
if(tutorial.day == day)
num++;
if(lab.day == day)
num++;
return num;
}
/* clashWith: to check whether this module clash with a Module called otherModule
* PRE-Condition :
* POST-Condition :
*/
public boolean clashWith(Module otherModule) {
if(lecture.clashWith(otherModule.lecture) || lecture.clashWith(otherModule.tutorial) || lecture.clashWith(otherModule.lab) )
return true;
if(tutorial.clashWith(otherModule.lecture) || tutorial.clashWith(otherModule.tutorial) || tutorial.clashWith(otherModule.lab))
return true;
if(lab.clashWith(otherModule.lecture) || lab.clashWith(otherModule.tutorial) || lab.clashWith(otherModule.lab))
return true;
return false;
}
}
class Timetable {
Vector<Module> listOfModule;
/* checkClash: to check whether otherModule clash with one of
* the modules in our timetable list.
* PRE-Condition :
* POST-Condition :
*/
public boolean checkClash(Module otherModule) {
for(Module c: listOfModule)
if(c.clashWith(otherModule))
return true;
return false;
}
/* add: to add a new module to the timetable list.
* PRE-Condition :
* POST-Condition :
*/
public void add(Module module) {
listOfModule.add(module);
}
/* count: to count number of classes on day.
* PRE-Condition :
* POST-Condition :
*/
public int count(String day) {
int count_day=0;
for(Module c: listOfModule)
count_day += c.count(day);
return count_day;
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num_operation;
String code ;
Timetable userTimetable = new Timetable();
num_operation = input.nextInt();
for(int i=0;i<num_operation;i++) {
if(input.next() == "MODULE") {
code = input.next();
String day;
int start, end;
Schedule getLecSche = new Schedule(input.next(),input.nextInt(),input.nextInt());
Schedule getTutSche = new Schedule(input.next(),input.nextInt(),input.nextInt());
Schedule getLabSche = new Schedule(input.next(),input.nextInt(),input.nextInt());
Module userModule = new Module(code, getLecSche, getTutSche, getLabSche);
System.out.println("Reached line 162");
if(!userTimetable.checkClash(userModule)) {
userTimetable.add(userModule);
System.out.println("Added");
}
else
System.out.println("Clashed");
}
else if(input.next() == "COUNT") {
code = input.next();
System.out.println(userTimetable.count(code));
}
}
}
}

Found it. You're using == to compare Strings. That only compares the object reference.
Use this instead:
if (input.next().equals("MODULE"))
//...
if(input.next().equals("COUNT"))
It is also worth mentioning that this will not catch "Count", "cOunT", "Module", "module", or "mOdulE" - you may want to use equalsIgnoreCase() instead.

In Timetable, you are never assigning a value to listOfModule:
Vector<Module> listOfModule;
Which causes a NullPointerException. You need to assign a new object to that reference:
Vector<Module> listOfModule = new Vector<Module>();

I think the problem is with input.next() here.
public String next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
UPDATE :
Removing the confusion for downvoters input.next() above is from statement if(input.next() == "MODULE") {

Related

How to write constructor that will accept 1 of 3 String values that I choose in the case (morning, evening, night)?

this is a subclass and am trying to shifts variable to accept only 1 of 3 values, that's morning evening night am a newbie so please forgive me for such a simple question
public class PartTimeStaffHire extends StaffHire
{
// instance variables - replace the example below with your own
private int workingHour
private double wagesPerHour
private String shifts;
private boolean terminated
This is subclass of StaffHire and accept all this variables and the last one am trying to accept only 1 of this 3 values
/**
* Constructor for objects of class PartTimeStaffHire
*/
public PartTimeStaffHire(int vacancy, String designation1, String typeofjob,
String staffName1, String joinDate, String qualification1, String appointed,
boolean joined, int hoursPerDay, double wagePerHour, String shift)
{
super(vacancy, designation1, typeofjob, staffName1, joinDate,
qualification1, appointed, joined);
workingHour = hoursPerDay;
wagesPerHour = wagePerHour;
shifts = shift;
if( shifts == "morning") {
shifts = "morning";
}
else if(shifts == "evening") {
shifts = "evening";
}
else if(shifts == "night") {
shifts = "night";
}
else {
System.out.println("Choose (morning, evening, night)" );
}
//(morning, evening, night)
}
public String shift()
{
if( shifts == "morning") {
shifts = "morning";
}
else if(shifts == "evening") {
shifts = "evening";
}
else if(shifts == "night") {
shifts = "night";
}
else {
System.out.println("Choose (morning, evening, night)" );
}
return shifts;
}
/**
* 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 print()
{
super.print();
System.out.println("The yearly salary is " + wagesPerHour);
System.out.println("Weekly working hours are " + workingHour;
System.out.println("##################" + shifts);
}
}
thanks in advance
If you know the possible values of a type, an enum is what you want to use.
So in this case you can create an enum Shift with the three possible constants:
public enum Shift {
MORNING,
EVENING,
NIGHT;
//this lets you convert a String such as `morning` to an enum constant
//if the enum not not one of the 3 constants (ignoring the case), this returns null. So you can use it to also validate the input.
public static Shift getShiftByName(String name) {
for(Shift s:values()) {
if(s.name().equalsIgnoreCase(name)) {
return s;
}
}
return null;
}
//if you want to convert it back to a String (for output), overwrite toString:
#Override
public String toString() {
//name() returns the constant's name as a String, such as "MORNING".
// since you use it as lowercase, overriding toString here makes sense
return name().toLowerCase();
}
}
You can then use it as
String strShiftInput = "morning";
Shift chosenChift = getShiftByName(strShiftInput);
if(chosenShift == null) {
//invalid input, handle accordingly
}
new PartTimeStaffHire(theOtherParameters, chosenShift);

Method to check "dutch" postal code in java

I'm trying to create a method in java to validate a dutch postal code.
the dutch postal code consist 6 characters which contain 4 numbers (first 4 chars) and 2 letters (last 2 chars) so for example 1010AB.
I made a boolean to return false if the postcode is not within standard and true if it is.
I'm getting stuck with checking the last 2 letters.
I've created a loop for the first 4 numbers, but I don't know how to go further from here to check the letters aswell.
My java method:
public static boolean checkPostcode(String postCode) {
boolean value = false;
if (postCode.length() == lengthPost) {
for (int i = 0; i < postCode.length(); i++) {
if (i <= 4) {
if (Character.isDigit(postCode.charAt(i)) {
value = true;
else{
if (Character.isLetter(postCode.charAt(i))) {
value = true;
}
}
}
}
}
}
return value;
}
You van ignore the last else, because that is the point where I get stuck....
If someone can help me that would be great!!
Thanks in advance
Solution using regex:
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(checkPostcode("1234AB"));
System.out.println(checkPostcode("5678MN"));
System.out.println(checkPostcode("0123AB"));
System.out.println(checkPostcode("1023AB"));
System.out.println(checkPostcode("1230AB"));
System.out.println(checkPostcode("AB1234"));
System.out.println(checkPostcode("123456"));
System.out.println(checkPostcode("ABCDEF"));
System.out.println(checkPostcode("12345A"));
System.out.println(checkPostcode("A12345"));
System.out.println(checkPostcode("A12345B"));
System.out.println(checkPostcode("1ABCDE6"));
System.out.println(checkPostcode("1ABCD6"));
}
public static boolean checkPostcode(String postCode) {
return postCode.matches("[1-9]{1}[0-9]{3}[a-zA-Z]{2}");
}
}
Output:
true
true
false
true
true
false
false
false
false
false
false
false
false
Non-regex solution:
public static boolean checkPostcode(String postCode) {
if (postCode.length() != lengthPost || postCode.charAt(0) == '0') {
return false;
}
if (postCode.length() == lengthPost) {
for (int i = 0; i < postCode.length(); i++) {
if (i < 4 && Character.isLetter(postCode.charAt(i))) {
return false;
}
if (i > 3 && Character.isDigit(postCode.charAt(i))) {
return false;
}
}
}
return true;
}
If I understand correctly, the first 4 symbols are digits, so the if condition should be
(i < 4)
because otherwise you check the first 5 symbols for a digit
While you could solve this problem with regular expressions, it is also possible to solve it along the lines you have chosen. I would write two helper methods, one to check that all characters within a given subsequence of a String are digits and another to check for letters. Like,
private static boolean allDigits(String s, int start, int end) {
for (int i = start; i < end; i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
private static boolean allLetters(String s, int start, int end) {
for (int i = start; i < end; i++) {
if (!Character.isLetter(s.charAt(i))) {
return false;
}
}
return true;
}
Then the checkPostcode can delegate to those two methods. Like,
public static boolean checkPostcode(String postCode) {
if (postCode != null && postCode.length() == 6) {
return allDigits(postCode, 0, 4) && allLetters(postCode, 4, 6);
}
return false;
}
And if you choose to use a regular expression compile it with a Pattern for better performance. Like,
private static Pattern POSTCODEPATTERN = Pattern.compile("\\d{4}[A-Za-z]{2}");
public static boolean checkPostcode(String postCode) {
return postCode != null && POSTCODEPATTERN.matcher(postCode).matches();
}

calling a set value method from another class

I'm creating a four digit class (like a clock) while calling methods from a two digit class.
The four digit class has two segments. When segment one reaches my set maximum value, the second segment must increase by one.
these are my methods from my first class:
/*
* method to set the value
*/
public void setValue(int anyValue){
if((anyValue < TOO_HIGH) && (anyValue >= 0)){
value = anyValue;}
}
/*
* method to set the value plus one
*/
public void setValuePlusOne(){
int tempValue = value + 1;
if(tempValue < TOO_HIGH){
value = tempValue;}
else{
value = 0;
// value = tempValue % TOO_HIGH;}
}
This is from my second four digit class.
/*
* method to set the increment
*/
public void setIncrement(int increment){
rightSegment.setValuePlusOne();
if(increment == 0)
leftSegment.setValuePlusOne();
}
I think there might be something wrong with my increment == 0. It doesn't compile when I try
if(rightsegment.setValuePlusOne()==0)
any advise would help. Thank you!!
setValuePlusOne(...) does not return anything. Call setValuePlusOne before the if and then use (rightsegment.getValue() == 0) for the if.
Please try the code below. Hope the below code will help you to achieve your implementation.
Instead of setting the TOO_HIGH integer value in the if else block of the below given code, you can set it in the RightSegment and LeftSegment classes respectively which is extending the Clock class.
Thanks
package stackoverflow;
public class Clock {
private int value;
private int TOO_HIGH;
private Clock rightSegment;
private Clock leftSegment;
/*
* method to set the value
*/
public void setValue(int anyValue, String position){
if(position.equals("right")){
TOO_HIGH = 60;
}else if(position.equals("left")){
TOO_HIGH = 13;
}
if((anyValue < TOO_HIGH) && (anyValue >= 0)){
value = anyValue;}
}
/*
* method to set the value plus one
*/
public void setValuePlusOne(){
int tempValue = value + 1;
if(tempValue < TOO_HIGH){
value = tempValue;}
else{
value = 0;
}
// value = tempValue % TOO_HIGH;}
}
/*
* method to set the i`ncrement
*/
public void setIncrement(int increment, Clock right, Clock left){
rightSegment = right;
leftSegment = left;
//rightSegment = new Clock();
//leftSegment = new Clock();
rightSegment.setValuePlusOne();
if(increment == 0){
leftSegment.setValuePlusOne();
}
}
public static void main (String args[]){
Clock clock = new Clock();
clock.rightSegment = new Clock();
clock.leftSegment = new Clock();
clock.rightSegment.setValue(12, "right");
clock.leftSegment.setValue(12, "left");
clock.rightSegment.setIncrement(0, clock.rightSegment, clock.leftSegment);
System.out.println("Time "+clock.leftSegment.value+":"+clock.rightSegment.value);
}
}

Constructor not setting values? Get method not working [duplicate]

When I try to run this program, the result is always null, 0 0. Why do the values of monthName, day, and year not show up when the getDay() method is invoked and printed on the screen.
public class Assignment1 {
public static void main(String[] args) {
//creates an array of type Date filled with two LongDate objects
Date [] collectionOfDates = { new LongDate("February",2,1996), new LongDate("February",13,1999) };
// loops through the array and displays output of getDate() for each object
for( int i = 0; i < collectionOfDates.length; i++ ) {
System.out.println( collectionOfDates[i].getDate() );
}
}
}
For your information, the LongDate class is a subclass of the Date class which contains methods editDay() and editYear() along with several others. The LongDate method is listed below.
Any help greatly appreciated, Thanks. Also, feel free to comment if you want more information.
public class LongDate extends Date {
private String monthName;
private int day;
private int year;
public LongDate() {
}
public LongDate(String m, int d, int y) {
super.editday(d);
super.edityear(y);
editMonth(m);
}
public void setDate(String m, int d, int y) {
monthName = m;
day = d;
year = y;
}
public String getDate() {
StringBuilder fullDate = new StringBuilder();
fullDate.append(monthName);
fullDate.append(" ");
fullDate.append(day);
fullDate.append(", ");
fullDate.append(year);
return fullDate.toString();
}
public String getShortDate() {
int month = 0;
if (monthName == "January") {
month = 1;
} else if (monthName == "February") {
month = 2;
} else if (monthName == "March") {
month = 3;
} else if (monthName == "April") {
month = 4;
} else if (monthName == "May") {
month = 5;
} else if (monthName == "June") {
month = 6;
} else if (monthName == "July") {
month = 7;
} else if (monthName == "August") {
month = 8;
} else if (monthName == "September") {
month = 9;
} else if (monthName == "October") {
month = 10;
} else if (monthName == "November") {
month = 11;
} else if (monthName == "December") {
month = 12;
}
StringBuilder shortDate = new StringBuilder();
shortDate.append(month);
shortDate.append("/");
shortDate.append(day);
shortDate.append("/");
shortDate.append(year);
return shortDate.toString();
}
protected String editMonth(String m) {
// asks person to try again if month is not capitalized and spelled properly
if (m != "January" && m != "February" && m != "March" && m != "April" && m != "May" && m != "June" && m != "July" && m != "August" && m != "September" && m != "October" && m != "November" && m != "December") {
m = Input.getString( "Invalid month. Please type the month again." );
return m;
} else
return m;
}
}
There's nothing in the constructor of LongDate which sets the fields (monthName, day, and year) that getDate() reads.
I assume that the Date#editDay() and Date#editYear() functions look similar to LongDate#editMonth(). Note that editMonth() does not assign a value to the monthName field!
You should compare your strings with equals() and not ==. The equals() method compares string values, whereas == compares object references, which is not what you want here. So change:
if (monthName == "January") {
to:
if (monthName.equals("January")) {
and similarly for the other comparisons.
Couple of issues. First:
public LongDate(String m, int d, int y) {
super.day(d);
super.year(y);
editMonth(m);
}
You don't show Date so it is unclear to us what day() and year() are supposed to do, but regardless:
public class LongDate extends Date {
private String monthName;
private int day;
private int year;
...
}
Your declarations of these fields are hiding any similar fields that the base presumably has. In any case, at no point in your constructor are you setting this.day or this.year to anything, and so, of course, they remain at their initial value of 0.
You need to clean up your code a bit. Either refer to the correct day and year, or make sure you are setting and getting the base class' version of those fields instead of redeclaring them in the subclass (again, not sure what your base implementation does).
You may want to have a look at the official tutorial on Inheritance. It's concise and well-written and covers topics like overriding methods, hiding fields, etc. I think it will give you a good starting point for solving your issues here.
And, of course, comparing strings with == here will lead to other issues in the future: How do I compare strings in Java?
Your editMonth method returns a string, instead it should set the month:
monthName = m;
Another option is to keep the editMonth method the same, but in your constructor put:
monthName = editName(m);

Combination Lock Aid

I am creating a Combination Lock class in Netbeans and I am confused as to why when I run the file I do not recieve any output. Anyone know what I am doing wrong? Any and all help would be greatly appreciated! Here is the code in my constructer class :
package combinationlock ;
/**
* A class to implement a combination lock with 26 dial positions
* and a three-letter combination
*
* #Carlos
*/
public class CombinationLock
{
// instance variable declarations go here
private boolean open ;
private int Count ;
private String position1 ;
private String position2 ;
private String position3 ;
private String first = "F" ;
private String second = "I" ;
private String third = "U" ;
/**
* Creates a lock with a given combination consisting of three upper-case characters.
* #param first the first letter of the combination
* #param second the second letter of the combination
* #param third the third letter of the combination
*/
public CombinationLock(String first, String second, String third)
{
this.first = first ;
this.second = second ;
this.third = third ;
open = false ;
Count = 0 ;
}
/**
* Set the dial to a position
* #param aPosition a String consisting of a single uppercase letter (A..Z)
*/
public void setPosition(String aPosition)
{
if (Count == 0)
{
position1 = aPosition ;
Count = Count + 1 ;
}
else if (Count == 1)
{
position2 = aPosition ;
Count = Count + 1 ;
}
else if (Count == 2)
{
position3 = aPosition ;
}
}
/**
* Try opening the lock
*/
public void tryToOpen()
{
if (first.equals(position1) && second.equals(position2) && third.equals(position3))
{
open = true ;
System.out.println("Its open!") ;
}
else
{
open = false ;
System.out.println("Wrong combination! Please try again.") ;
}
}
/**
* Check whether the lock is open
* #return true or false indicating whether the lock is open
*/
public boolean isOpen()
{
return open ;
}
/**
* Close the lock and print a message indicating that the lock is now closed
*/
public void lock()
{
Count = 0 ;
open = false ;
System.out.println("You re-apply the lock") ;
}
}
And here is the code I used in my tester class:
package combinationlock ;
import javax.swing.JOptionPane ;
/**
*
* #author Carlos
*/
public class CombinationLockTester
{
public static void main (String[] args)
{
CombinationLock MasterLock = new CombinationLock("A", "B", "C");
String input = JOptionPane.showInputDialog
("Please enter first letter.") ;
MasterLock.setPosition(input) ;
String input2 = JOptionPane.showInputDialog
("Please enter second letter.") ;
MasterLock.setPosition(input2) ;
String input3 = JOptionPane.showInputDialog
("Please enter third letter") ;
MasterLock.setPosition(input3);
System.out.println("The combination entered was " +input + input2 +input3) ;
}
}
You are setting positions on MasterLock but not calling the tryToOpen method. Try this and see if you get any output:
MasterLock.tryToOpen();
Which should be called after the three calls to setPosition.

Categories