Reputation: 33
Can you please tell me what is wrong with the following java code.
I am trying to collect input from the user through Scanner
class object then store it in an array
by using while but it would be infinite loop if i don't supply a break
condition , so i thought to break
when the input equals "q", but it didn't work.
import java.util.*;
public class ProjectOne{
public static void main (String []arg){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String x = input.next();
while ( input.hasNext()){
if (x !="q"){
one.add(input);
}
if (x == "q")
{
break;
}
System.out.println(one);
}
}
}
Upvotes: 2
Views: 1232
Reputation: 1321
Scanner reads everything before your ENTER - the whole line you input.
I think that is what you need:
import java.util.ArrayList;
import java.util.Scanner;
public class ProjectOne
{ public static void main (String []arg ){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String pattern;
String x = input.next();
while (true){
String line = input.next();
if(line.contains("q"))break;
else{
x = x + " " + line;
}
}
System.out.println(x);
}
Upvotes: 0
Reputation: 5705
You don't compare String
with ==
. Use .equals()
like
if (!x.equals("q")){
and
if (x.equals("q"))
Note : I think that you aren't using Scanner
correctly. You take the input, but keep checking x
, instead of the input.
Upvotes: 1
Reputation: 5803
You are not reading updated value from Scanner
. Below is updated code for your reference after correcting formatting and other errors. Also, instead of ==
sign, use equals()
method for string comparison -
import java.util.*;
public class ProjectOne{
public static void main (String []arg ){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String x = null;
while ( input.hasNext()) {
x = input.next();
if (!x.equals("q")) {
one.add(x);
}
if (x.equals("q")){
break;
}
}
System.out.println(one);
}
Upvotes: 0
Reputation: 2109
Do not compare strings like x =="q"
USE .equals function in java for string comparison.
Replace your code with: x.equals("q") for x =="q"
and !x.equals("q") for x !="q"
Upvotes: 0