Getting "cannot find symbol" error with reader.nextLine()

Here is my code (it is code to reverse a given string)

    import java.util.Scanner;

public class ReversingName {
    public static String reverse(String text) {
    // write your code here
    int strlenght= text.length();
    int i=1;
    String str= "";
    while (i<=strlenght){
        char test= text.charAt(strlenght-1);
        str=str+test;
    }
    return str;
}


public static void main(String[] args) {
    System.out.print("Type in your text: ");
    String text = reader.nextLine();
    System.out.println("In reverse order: " + reverse(text));
}
}

But I cannot take in input because when I try to take the string input I get a “cannot find symbol error” even though I have clearly defined the variable “text”.

This question is from MOOC.fi’s Java OOP course, and can be found here (question 52, if it helps): https://materiaalit.github.io/2013-oo-programming/part1/week-3/

Solution:

reader is never declared. From the looks of things, it seems as though it’s supposed to be a Scanner instance:

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in); // Declare and initialize reader
    System.out.print("Type in your text: ");
    String text = reader.nextLine();
    System.out.println("In reverse order: " + reverse(text));
}

is this use of objects redundant and/or inefficient?

I’m fairly inexperienced with using objects so I would really like some input.

I’m trying to remove comments from a list that have certain “unwanted words” in them, both the comments and the list of “unwanted words” are in ArrayList objects.

This is inside of a class called FormHelper, which contains the private member comments as an ArrayList, the auditList ArrayList is created locally in a member function called populateComments(), which then calls this function (below). PopulateComments() is called by the constructor, and so this function only gets called once, when an instance of FormHelper is created.

private void filterComments(ArrayList <String> auditList) {
    for(String badWord : auditList) {
        for (String thisComment : this.comments) {
            if(thisComment.contains(badWord)) {
                int index = this.comments.indexOf(thisComment);
                this.comments.remove(index);
            }
        }
    }
}

something about the way I implemented this doesn’t feel right, I’m also concerned that I’m using ArrayList functions inefficiently. Is my suspicion correct?

Solution:

It is not particularly efficient. However, finding a more efficient solution is not straightforward.

Lets step back to a simpler problem.

private void findBadWords(List <String> wordList, List <String> auditList) {
    for(String badWord : auditList) {
        for (String word : wordList) {
            if (word.equals(badWord)) {
                System.err.println("Found a bad word");
            }
        }
    }
}

Suppose that wordList contains N words and auditList contains M words. Some simple analysis will show that the inner loop is executed N x M times. The N factor is unavoidable, but the M factor is disturbing. It means that the more “bad” words you have to check for the longer it takes to check.

There is a better way to do this:

private void findBadWords(List <String> wordList, HashSet<String> auditWords) {
    for (String word : wordList) {
        if (auditWords.contains(word))) {
            System.err.println("Found a bad word");
        }
    }
}

Why is that better? It is better (faster) because HashSet::contains doesn’t need to check all of the audit words one at a time. In fact, in the optimal case it will check none of them (!) and the average case just one or two of them. (I won’t go into why, but if you want to understand read the Wikipedia page on hash tables.)


But your problem is more complicated. You are using String::contains to test if each comment contains each bad word. That is not a simple string equality test (as per my simplified version).

What to do?

Well one potential solution is to split the the comments into an array of words (e.g. using String::split and then user the HashSet lookup approach. However:

  • That changes the behavior of your code. (In a good way actually: read up on the Scunthorpe problem!) You will now only match the audit words is they are actual words in the comment text.

  • Splitting a string into words is not cheap. If you use String::split it entails creating and using a Pattern object to find the word boundaries, creating substrings for each word and putting them into an array. You can probably do better, but it is always going to be a non-trivial calculation.

So the real question will be whether the optimization is going to pay off. That is ultimately going to depend on the value of M; i.e. the number of bad words you are looking for. The larger M is, the more likely it will be to split the comments into words and use a HashSet to test the words.

Another possible solution doesn’t involve splitting the comments. You could take the list of audit words and assemble them into a single regex like this: \b(word-1|word-2|...|word-n)\b. Then use this regex with Matcher::find to search each comment string for bad words. The performance will depend on the optimizing capability of the regex engine in your Java platform. It has the potential to be faster than splitting.


My advice would be to benchmark and profile your entire application before you start. Only optimize:

  1. when the benchmarking says that the overall performance of the requests where this comment checking occurs is concerning. (If it is OK, don’t waste your time optimizing.)

  2. when the profiling says that this method is a performance hotspot. (There is a good chance that the real hotspots are somewhere else. If so, you should optimize them rather than this method.)

Note there is an assumption that you have (sufficiently) completed your application and created a realistic benchmark for it before you think about optimizing. (Premature optimization is a bad idea … unless you really know what you are doing.)

Copy constructor isn't working

iv’e just started learning about copy constructors in java (OOP).
but for some reason it doesn’t work for me. this is what I did :
class Date:

public class Date {
private int day;
private int month;
private int year;
//regular build function
public Date(int day,int month, int year)
{
  this.day=day;
  this.month=month;
  this.year=year;
}    
//copy constructor
public Date (Date date){
    this.day = date.day;
    this.year = date.year;
    this.month = date.month;
}   
public String toString()
{
  return this.day+"/"+this.month+"/"+this.year;
}
}

the class Passport :

 public class Passport {
private String name; //the name property
private int number; //the number property
private Date expiryDate; //the expiryDate property
//a regular building constructor
public Passport(String name,int number, Date expiryDate)
{
  this.name=name;
  this.number=number;
  Date copyExpiryDate = new Date(this.expiryDate);  
  this.expiryDate = copyExpiryDate;
} 
//a copy constructor
public Passport(Passport passport)
{
  this.name = passport.name;
  this.number = passport.number;
  this.expiryDate = passport.expiryDate;
}   

the main method is :

 import java.util.*;
 public class Check {
static Scanner reader=new Scanner(System.in);
//checking if the classes are working properly
public static void main(String[] args){
    int numtraveler,passNum,passDay,passMonth,passYear,pay,planDay,planMonth,planYear;
    String name; 
    boolean isPay=false;
    System.out.println("how many travelers are you?");
    numtraveler=reader.nextInt();
    for(int i=0 ; i<numtraveler ; i++){
        System.out.println("enter your passport : ");
        System.out.println("enter name : ");
        name=reader.next();
        System.out.println("enter passport number : ");
        passNum=reader.nextInt();
        System.out.println("enter your passport's expiry date : (day then month then year) ");
        passDay=reader.nextInt();
        passMonth=reader.nextInt();
        passYear=reader.nextInt();
        Date d1=new Date(passDay,passMonth,passYear);
        System.out.println(d1);
        Passport p1=new Passport(name,passNum,d1);
        System.out.println(p1);
        Traveler t1=new Traveler(p1,isPay);
        System.out.println("do you want to pay? :(enter o if yes and 1 if not) ");
        pay=reader.nextInt();
        if(pay==0){
            t1.pay();
        }
        System.out.println("when are you planning to travel?(enter day then month then year)");
        planDay=reader.nextInt();
        planMonth=reader.nextInt();
        planYear=reader.nextInt();
        Date dPlan=new Date(planDay,planMonth,planYear);
        if(t1.checkTravel(dPlan)){
            System.out.println("The travel is possible");
        }
        else
            System.out.println("The travel isn't possible");            
    }
}
}

I have omitted some unimportant information from the class- the get and set from date, some other functions they both had and another class called Traveler because They aren’t that relevant to the problem. The Traveler class uses the Passport copy constructor but it has the same problem there.
When I run the main method it gets to the date,creates the object d1 and displays the date but when it gets to creating the object p1 from the Passport class it run an error : “Exception in thread “main” java.lang.NullPointerException”.
However, when I change in the Passport class to :

 Date copyExpiryDate = new Date(expiryDate.getDay(), 
        expiryDate.getMonth(), expiryDate.getYear());

it workes. anyone knows what I’m doing wrong with the copy constructor?
I’ll be very thankful for any one who helps!

Solution:

In the Passport copy constructor you are not creating a copy of the expiration date.

Change

public Passport(Passport passport)
{
  this.name = passport.name;
  this.number = passport.number;
  this.expiryDate = passport.expiryDate;
} 

to

public Passport(Passport passport)
{
  this.name = passport.name;
  this.number = passport.number;
  this.expiryDate = new Date(passport.expiryDate);
}  

The other constructor also has an issue.

public Passport(String name,int number, Date expiryDate)
{
  this.name=name;
  this.number=number;
  Date copyExpiryDate = new Date(this.expiryDate);  
  this.expiryDate = copyExpiryDate;
}

should be

public Passport(String name,int number, Date expiryDate)
{
  this.name=name;
  this.number=number;
  this.expiryDate = new Date(expiryDate);
} 

i.e. you should create a copy of the passed expiryDate, not a copy of this.expiryDate.

python static overloading of member function

I’m new to python and have a simple question: Is it possible to statically overload a member fuction? Like for example so:

class A:
    text=""
    def __init__(self, text):
        self.text = text

    def print(self):
        print (self.text)

    @staticmethod
    def print():
        print ("static")

a = A("test") 
a.print()

In this case “static” is printed out. Is it impossible to call the member function if a static function with the same name exists? And if not, who do I call it?

Solution:

You aren’t overloading the method; you are replacing it with the static method. You’ll have to pick a different name for the static method.

python static overloading of member function

I’m new to python and have a simple question: Is it possible to statically overload a member fuction? Like for example so:

class A:
    text=""
    def __init__(self, text):
        self.text = text

    def print(self):
        print (self.text)

    @staticmethod
    def print():
        print ("static")

a = A("test") 
a.print()

In this case “static” is printed out. Is it impossible to call the member function if a static function with the same name exists? And if not, who do I call it?

Solution:

You aren’t overloading the method; you are replacing it with the static method. You’ll have to pick a different name for the static method.

python .sort() has higher priority for __lt__ than __gt__?

I have seen similar questions, but they did not answer why python __lt__ has higher priority than __gt__?

Quick example, let me give a superclass and a subclass:

class Person(object):
    id = 0
    def __init__(self, name):
        self.name = name
        self.id = Person.id
        Person.id += 1

    def __str__(self):
        return self.name

    def __lt__(self, other):
        return self.id < other.id

class SubPerson(Person):
    def __gt__(self, other):
        return self.name > other.name

Here in superclass Person, I created a __lt__ method, to compare based on Person’s self.id. In sub class SubPerson, I created a __gt__ method to compare based on the self.name.

What I found is that if I created a number of SubPerson instances in a list:

s1 = SubPerson('WWW'); s1.id = 14
s2 = SubPerson('XXX'); s2.id = 12
s3 = SubPerson('YYY'); s3.id = 11
s4 = SubPerson('ZZZ'); s4.id = 13
lst2 = [s2, s1, s4, s3]
lst2.sort()
print([i.__str__() for i in lst2])  # >>> ['YYY', 'XXX', 'ZZZ', 'WWW']

What I found is that:
if __lt__ is defined in superclass, then even if you define __gt__ in subclass, it will still sort by the __lt__ method in superclass

But if it is the other way around, define __gt__ in superclass and __lt__ in subclass, then it will then sort by __lt__ in subclass

If the two method names are the same (both lt or both gt), obviously, the subclass will override superclass, as it should be.

But it seems when they are different, it follows a different rule: by whatever __lt__ defines. I’ve also noticed that even if in one class, if both __lt__ and __gt__ are defined (based on different things, it will still sort by __lt__ method)

SO back to my question, is my observation true or not? and since I am a beginner, and I have not read through the whole python documents, can somebody point me out where in the documents that this rule is written.

Solution:

list.sort uses only < comparisons. This is documented.

Binary operators like < will try the left-hand operand’s method first unless the right-hand operand’s class is a subclass of the left-hand operand’s class. The other operand’s method will only be considered if the first method is missing or returns NotImplemented. The left-hand operand’s method for < is __lt__, and the right-hand operand’s method is __gt__. This is also documented.

Since all your list elements have the same class and __lt__ always succeeds, only the __lt__ methods end up getting called.

Python: How to initialise a OOP List with some values already known?

I am trying to get into Object Oriented Programming but am getting stuck on something which is probably very simple. I want to have an object which is a list, but which starts with having some values passed into it.

Example:

class superList(list):
    def __init__(self,startingValues):
        self = startingValues

myList = superList([1,2,3])
myList.append(4)
print(myList)

I want the output of this to be [1,2,3,4]. If anyone could help, I would be very thankful!

Solution:

Assigning to self isn’t useful; you are just assigning to a local name that goes away after __init__ returns. Instead, you need to use __new__, and call the parent’s class’s __new__ method.

class SuperList(list):
    def __new__(cls, starting_values):
        return list.__new__(cls, starting_values)

Another approach is to use __init__, and just append the values in place:

class SuperList(list):
    def __init__(self, starting_values):
        self.extend(starting_values)

As pointed out in the comments, though, you would get the exact same result by not overriding either method:

class SuperList(list):
    pass

because you aren’t doing anything except invoking parent-class behavior in either method. In the absence of a defined SuperList.__new__, for example, SuperList([1,2,3]) just calls list.__new__(SuperList, [1,2,3]) anyway.

More interesting is when the class itself (at least, in part) determines behavior beyond using the values passed by the caller. For example:

class SuperList(list):
    def __init__(self, starting_values):
        self.extend([2*x for x in starting_values])

or

    def __init__(self):
        self.extend([1,2,3])

Why can instance methods be called as class methods in Python 3?

Consider the following class:

class Foo(object):
    def bar(self):
        print(self)

In Python 2 (2.7.13), calling bar() as a class method raises an exception:

>>> Foo.bar('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as first argument (got str instance instead)

>>> Foo.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead)

When bar() is called as an instance method it recognizes self as the instance when called without arguments

>>> Foo().bar('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bar() takes exactly 1 argument (2 given)

>>> Foo().bar()
<__main__.Foo object at 0x10a8e1a10>

In Python 3 (3.6.0), when calling bar() as a class method, the first argument is accepted as self:

>>> Foo.bar('hello')
hello

>>> Foo.bar()
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bar() missing 1 required positional argument: 'self'

Calling bar() as an instance method works as in Python 2

>>> Foo().bar('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bar() takes 1 positional argument but 2 were given

>>> Foo().bar()
<__main__.Foo object at 0x104ab34a8>

Solution:

On Python 3, Foo.bar is just that bar function you wrote. It takes one parameter, which happens to be named self, and prints it. You can call that function on anything, and it will print whatever argument you pass it.

On Python 2, Foo.bar isn’t quite the bar function you wrote. When you access Foo.bar, Python generates an unbound method object wrapping the bar function. The unbound method object works mostly like the bar function, with the main difference of validating that its first argument is an instance of Foo. You could do

Foo.bar(some_foo_instance)

which would work like some_foo_instance.bar(), but calling Foo‘s implementation, bypassing any overrides in subclasses. You couldn’t do Foo.bar('hello'), though.

Python 3 removed unbound method objects. They don’t exist any more. That makes the language a bit simpler, but it removes the validation unbound method objects used to perform.

Python multiple inheritance is not showing class variables or method of second inherited base class

Hello awesome community,
I was learning the OOPS concepts with python as a part of my curriculum. I am having a problem with multiple inheritance in python. The following is my code:

#!/usr/bin/env python

class Base1(object):
    def __init__(self):
        self.base1var = "this is base1"


class Base2(object):
    def __init__(self):
        self.base2var = "this is base2"

class MainClass(Base1, Base2):
    def __init__(self):
        super(MainClass, self).__init__()


if __name__ == "__main__":
    a = MainClass()
    print a.base1var
    print a.base2var

and when running, I am getting the following error

print a.base2var
AttributeError: 'MainClass' object has no attribute 'base2var'

If I swap the order of classes inherited, the variable name in the error changes accordingly.

Am I using super() wrong when I want to call the constructors of the two inherited classes?

How can I correctly inherit from multiple base classes and use the variables and methods in the main class without this error?

Thank you.

Solution:

You need to add a super call to Base1 so that Base2’s __init__ will get called after Base1’s. You can also add a super call to Base2. It’s not necessary, but it won’t hurt.

class Base1(object):
    def __init__(self):
        super(Base1, self).__init__()
        self.base1var = "this is base1"

class Base2(object):
    def __init__(self):
        #super(Base2, self).__init__()
        self.base2var = "this is base2"

class MainClass(Base1, Base2):
    def __init__(self):
        super(MainClass, self).__init__()


if __name__ == "__main__":
    a = MainClass()
    print a.base1var
    print a.base2var

output

this is base1
this is base2

BTW, you really should be using Python 3. super is much nicer in modern Python. 🙂

Implementing a composition relationship in an abstract class definition

I’m going through past exam papers for an OOP exam and I’ve come across a question:
Could the below class definition be used to implement a composition relationship between the classes Person and Brain?

abstract class Person{
   private Brain brain;
   Person(Brain humanBrain) {
      brain = humanBrain;
   }
}

I was under the impression that from the code given there is already a composition relationship between the two however as the question also asks for code samples I presume I’m wrong. An explanation of how to implement the composition or moreover why this already isn’t considered a composition relationship between the two would be appreciated.

Solution:

We know the UML Composition definition and we can find a lot of examples in SO and internet. But, I think we should look in-depth.

First of all: Clarification about Composition.
In Composition (see reference):

if a composite (whole) is deleted, all of its composite parts are
“normally” deleted with it.

Consider this example:

class Person {
   private final Brain brain;
   Person(Brain humanBrain) {
      brain = humanBrain;
   }
}

And in other parts of code we can define like this:

Brain b = new Brain(); 
       // or we have an instance of Brain in other scopes
       // not exactly in this scope

Person p1 = new Person(b);
Person p2 = new Person(b);

So, in this code, we can set one instance of Brain to two different Persons.

Note: In composition, we should manage the life cycle of instances. Only defining a private final of any class, do not show the Composition between them.

For example the below example can be a Composition. Because instances of “Part” deleted when the “whole” is deleted:

public class House {    
   private final Room room;

   public House() {    
       room = new Room();
   }
}

In Composition:
The “whole” may directly be responsible for creation or destruction of the “part”. Or it may use a “part” that has been already created and managed from external of class (by other parts of code). In this case, deletion of “part” should be managed by external code and the “part” should be deleted immediately after the “whole” deletion.

We should establish a mechanism to delete “part” when the “whole” is deleted. If we do not delete the “part” and use it in other “wholes” it is aggregation.

To sum up
Detecting the Composition in source code needs to have whole implementation of code. And we should ensure that the “part” is deleted immediately when the “whole” is delete.

The other point in the question is abstract. So we don’t have Object Composition or Object Aggregation in that code.

Finally: the relationship in the question is Composition (only based on the concept of Person and Brain). But, from the given source code it is not Composition yet.