[Solved] Java ArrayList / Scope (Answer: logical error) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

[Solved] Java ArrayList / Scope (Answer: logical error)

I'm trying to complete a challenge posted by Riya https://www.sololearn.com/post/1748360/?ref=app I wrote my code in Python and it works as expected. However I have difficulity in porting my code to Java. (Just ignore the default input as 100, I don't have any idea how to implement set a default user input in Java.) The code does run, but it prints a lots of empty array instead of the result array. I think I used the ArrayList wrongly, or messing with the scope. Any idea what went wrong? https://code.sololearn.com/cPqK4ns3Z5IS/?ref=app https://code.sololearn.com/cYpU3DXv8JIl/?ref=app

10th Nov 2023, 6:38 AM
Wong Hei Ming
Wong Hei Ming - avatar
8 Answers
+ 5
Lots of logical errors and a few mistakes of style. First you basically skipped all nonprime numbers, and primes are not abundant. You are really not using the prime-ness anyway so it can be removed. In Java we declare the types as interface, when possible (in anticipation of possible future refactor if we want to change the concrete type. List<Integer> res = new ArrayList<>(); You were clearing the divisors at the wrong spot. Your third loop had to be moved outside one level. And the indexing of the list begins with 0, not 1. You were also printing inside the loop, had to move outside. I also added the code for taking optional input with default value, using the hasNext method of Scanner. https://code.sololearn.com/ciZM1bUI8JaC/?ref=app
10th Nov 2023, 8:21 AM
Tibor Santa
Tibor Santa - avatar
+ 3
Tibor Santa & Brian Thanks! Java is so verbose to me. Basically I wrote the code on my pc with Notepad++ and comply it myself. It is easy to lost track of block with all the curly brackets. It was funny how I didn't notice I used the isPrime method wrongly. Also I didn't know we can refactor a ArrayList (or a Collections type?). I have an impression that we can't change the variable datatype once it is declare. However there is a problem left behind. The hasNext method combined with if...else... has no problem on playground. When I try it on my pc, hitting ENTER only return a blank line. It is waiting for the next input, much like stuck in a loop. After it is solved, I would like to add try...catch... to test my error handling skill. https://code.sololearn.com/cksb32wjRUOO/?ref=app
10th Nov 2023, 9:16 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 3
I want to offer you some more background to understand my point about interface / subclass. Java and many similar object-oriented languages have developed certain rules and principles, how the fundamental features such as polymorphism, inherintance and encapsulation, can be used effectively to create more durable, robust, and reliable programs. These principles may not seem to make much sense first, as long as you write small programs like this. But as soon as you start working on a larger system with many classes and code dependencies, and eventually you have to modify and extend the code, it will be very important how easy it is to make additions and create new features to an existing codebase, with as little effort as possible. This is where the SOLID principles will be helpful, and basically you have to follow them right from the start, to prevent future headaches :) https://en.wikipedia.org/wiki/SOLID And particularly the rule that deals with subclasses and inheritance, is the Liskov Substitution Principle (that is the L in SOLID). https://www.baeldung.com/java-liskov-substitution-principle It is a deep rabbit hole, and will take some time to fully understand and appreciate it. But these rules are widely used and adopted in the software industry, and not only in Java.
10th Nov 2023, 10:27 AM
Tibor Santa
Tibor Santa - avatar
+ 3
Those are some cool links and great information Tibor Santa, thanks!
10th Nov 2023, 6:55 PM
Ausgrindtube
Ausgrindtube - avatar
+ 2
Yes, Java is definitely much more verbose than Python. It is correct that you cannot change the type of a variable, once you declare it. The reason why this works and is preferable, is polimorphism. List<Integer> res = new ArrayList<>(); List is an interface, and ArrayList is a class that implements the List interface. There are also other classes which implement List, for example LinkedList, Stack, and Vector. They share the common methods of the List interface, so it doesn't matter if the object is instantiated as ArrayList or LinkedList, it will act as a List either way, but maybe the internal mechanics will be different, and the developer can choose the type that better fits the program requirement. Similarly the return value of a method, is preferred to be a List rather than an ArrayList. Using the Scanner properly on Sololearn is just as tricky as with other languages, you are right that in a normal console environment you may better use a try-catch block to handle bad or missing input. You can also use Integer.valueOf() method to convert a string to a number.
10th Nov 2023, 10:12 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Tibor Santa Integer.valueOf() is a good idea! I put it along with try-catch block, and it is working well in the playground. Although I not a computer science student in university, I did take a few courses about about computer. Inherintance and encapsulation is not that difficult. <Man>, <Female>, <Human>, <Cat> all can be under a class <Live Form>, as they are living being, under the house of <Live Form>. Pressing a remote button to switch TV on and off is encapsulation, because we don't need to know how the remote works. We only concern the output (TV of/off). But I have difficulity to understand polymorphism. I need some analogy examples to understand the concept. Maybe I should re-read the material about OOP in here. https://code.sololearn.com/cI7uV1L9b948/?ref=app
10th Nov 2023, 10:59 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
There is something wrong in the logic. For some reason the comparison (total>num) is never true, so it never reaches the line that adds num to the result array.
10th Nov 2023, 7:56 AM
Brian
Brian - avatar
+ 1
I take the time to read the wiki link, and make a short summarization. And it maybe wrong. (Another link is a bit long and saved for later.) Single-Responsibility One object, function and method only responsible for only one purpose. Other words: No multi-tasking. Open-Close Behavior of a software entity cannot be change from outside (open), yet the output can be modify or extended (close). Example: A game support mod changes a gameplay (open) but not changing the game’s code itself (close). Liskov Substitution In a program a sub-class can replace its' parent class without breaking the program. The details in wiki are a bit complicated. Below explanation maybe wrong. A sub-class can inherit from different classes, but it may bring too many method into that sub-class and it cannot represent any of it parent class. To make Liskov substitution holds true, a sub-class should only have one parent class, no parallel level of parents or inherit from different class branch. Interface Segregation From the Origin section in the wiki link, there is a one big library responsible for all printer functions. When a single action is called, the hold library must be loaded and executed. In such an action call will consume loads of memory to store the all the methods, while most of them are not required by the action. Workaround: Break down the large library into smaller library, each is responsible for particular jobs. (It is similar to Single-Responsibility to me, but the responsibilities are highly related.) And add a middle-man to make communication between library and action to increase code reuse opportunities. Dependency inversion Very much the same as Interface Segregation. Cannot figure out the difference yet.
10th Nov 2023, 2:56 PM
Wong Hei Ming
Wong Hei Ming - avatar