Heshamy Heshamy - 3 months ago 25
Java Question

String input until dot is entered

I want to make a program that keeps getting string input and only stops when "." is entered, any ideas how to make it?

I understand that I need to make a string array, but what's the length I'm gonna give it if I dont know how many strings the user will enter?

This is my first time to use this website, so excuse me for any mistakes.

Thank you.

Edit:
Here's a code that is confusing me. I keep entering dots but the for loop never breaks. Also the length is currently 10, how can I make it unlimited until the input is a dot?

Scanner s=new Scanner(System.in);
String[] x = new String[10];
for(int i=0;i<10;i++)
{
x[i]=s.next();
if(x[i]==".")
break;
}

Answer
Scanner s=new Scanner(System.in);
ArrayList<String> inputs = new ArrayList<>();
while (true) {
    inputs.add(s.next());
    if(inputs.get(inputs.size().equals("."))
        break;
}

Remember to import ArrayList. Check the documentation for more information about ArrayList. In java == is an operator used for comparing references. your new String won't have the same reference as "." which will be created at compilation time.

equals() method is used for comparing if the objects equal. In case of String it compares char by char to see if they are all the same. If yes, it returns true. False otherwise.

Remember to always @Override the public boolean equals() in your class. You have to decide what it means that to object of a certain class are equal and implement it. it'll be useful if you read this topic. It's widely described there.