Hello everyone,
There is something weird with my loop I can't understand. Here is my loop now :
while(true)
{
String s = reader.readLine();
if(s.isEmpty() || s == "") break;
else
{
listCat.add(CatFactory.getCatByKey(s));
}
}
The code seems to work when it is written like this.
Nonetheless, if I change it like this
while(true)
{
if(reader.readLine().isEmpty() || reader.readLine() == "") break;
else
{
listCat.add(CatFactory.getCatByKey(reader.readLine());
}
}
I get an error.
The only difference is using a String variable instead of raw using reader.readLine().
What is wrong ?
package fr.codegym.task.task14.task1404;
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Cat> listCat = new ArrayList<>();
while(true)
{
String s = reader.readLine();
if(s.isEmpty() || s == "") break;
else
{
listCat.add(CatFactory.getCatByKey(s));
}
}
for(Cat cat : listCat)
{
System.out.println(cat);
}
}
static class CatFactory {
static Cat getCatByKey(String key) {
Cat cat = null;
if ("sauvage".equals(key)) {
cat = new MeanCat("Griffeur");
} else if ("miss".equals(key)) {
cat = new NiceCat("Missy");
} else if ("fil".equals(key)) {
cat = new NiceCat("Filoute");
} else {
cat = new Cat(key);
}
return cat;
}
}
static class Cat {
private String name;
protected Cat(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String toString() {
return "Je m'appelle " + getName() + ", et je suis un chat de gouttière";
}
}
static class MeanCat extends Cat {
MeanCat(String name) {
super(name);
}
public String toString() {
return "Je m'appelle " + getName() + ", et je vais t'arracher les yeux";
}
}
static class NiceCat extends Cat {
NiceCat(String name) {
super(name);
}
public String toString() {
return "Je suis un gentil chaton et je m'appelle " + getName();
}
}
}