Using a while loop in an ArrayList - java

I'm new to programming and to this website, so here goes.
I wanted to write a program that would allow as many input strings as possible to be added to an ArrayList. So I used a while loop in the following code. What I intended was for the loop to break if the input was 0.
import java.util.*;
public class AddToList2
{
static Scanner q = new Scanner(System.in);
public static void main(String[] args)
{
ArrayList<String> inputlist = new ArrayList<String>();
while (true)
{
System.out.print("Enter something here: ");
String x = q.nextLine();
inputlist.add(x);
if (x.equals("0"));
break;
}
}
The program was compiled without error, but sadly, when I ran the program many times, the loop broke no matter what the input was. Any way to solve this?
Well, that was careless of me! Anyway, I had created that program in order to find out what was wrong with this:
ArrayList<String> endangeredlist = new ArrayList<String>();
ArrayList<Integer> popn = new ArrayList<Integer>();
while (true)
{
System.out.print("Name an animal: ");
String animal = q.nextLine();
endangeredlist.add(animal);
if (animal.equals("EXTERMINATE"))
break;
q.next();
System.out.print("How many are left in the wild? ");
int numberleft = q.nextInt();
popn.add(new Integer(numberleft));
}
(This is part of a much larger program.) My intention was for the loop to break when the animal name input was EXTERMINATE. Sadly the program throws a NoSuchElement exception if the input first time round was EXTERMINATE, and if I had inputted something else first the loop would start, but then inputting EXTERMINATE second time round does not break the loop. Why is that?

You have an extraneous semicolon after your if, which effectively makes it
if (x.equals("0")) { }
break;

You have a semi-colon at the end of your condition.
This turns the break into a statement of its own, without the condition.

Your if statement is broken
if (x.equals("0"));
This is basically saying if (x.equals("0")) do nothing...
This is one of the reasons why you should use parenthesis around your if statements
if (x.equals("0")) {
break;
}

Related

Java: how to reject incorrect input and wait for proper input using Scanner

This is the basic setup for a little console-based quiz game. The answers are numbered. I want the player to give the answer number. If the input is not a number, then my program should give a warning, and wait for proper input.
Instead, what I get (after inserting something that is not a number) is an infinite loop of asking the question and presenting the answers again.
public static void main(String[] args) {
boolean quizActive = true;
while(quizActive) {
presentQuestion();
presentAnswers();
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
String choice = s.next();
if (!NumberUtils.isNumber(choice)) {
presentText("Please insert the answer number.");
} else {
System.out.println("You made a choice!");
checkAnswer(choice);
quizActive = false;
}
s.close();
}
}
}
What am I doing wrong here?
If you do not want to question and answers be presented each time move presentQuestion() and presentAnswers() outside the loop.
But main problem is that you closing Scanner.
Remove s.close(); and move Scanner s = new Scanner(System.in); outside of the loop.
I really don't get the point in using scanner for acquiring user input.
The scanner class is perfect to process structured input from a flat file with known structure like an CSV.
But user input need to deal with all the human imperfection. After all the only advantage you get is not needing to call Integer.parseInt() your yourself at the cost to deal with the not cleared input when scanne.nextInt() fails...
So why not using InputStreamReader aside with a loop suggested by others?
Here an Example :
public class Application {
public static void main(String [] args) {
System.out.println("Please insert the answer number. ");
while (true) {
try {
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
System.out.println("You made a choice!");
checkAnswer(choice);
break;
} catch (Exception e) {
System.out.println("Invalid Number, Please insert the answer number ");
}
}
}
}
You started your Quiz in a loop which is regulated by your quizActive boolean. That means that your methods presentQuestion() and presentAnswers() get called every time the loop starts again.
If you don't input a number but a character for example, your program will run the presentText("Please insert the answer number.") and start the loop again. As it starts the loop again, it will call the methods presentQuestion() and presentAnswers().
To stop that, you can do another loop around the input-sequence. Also your Scanner s = new Scanner(System.in) should be outside the loop. And you shouldn't close your Scanner right after the first input and then open it again!
if you want a code example, please tell me :)

Can still enter input even outside loop

Why is that I can still an input even it's outside the while loop?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
while(true){
}
}
First, you don't need a while loop to take any input and your loop is practically useless since its not being used. Second, That loop is bad since any other loops you might have in your code will be unreachable. unless you specify a way to break the loop using break; or flags e.g.:
boolean myCondition = true;
while(myCondition){}
or use break:
while(true){
if(whatever){
break;
}
}
Then again you don't need any of this since your not dealing with multiple inputs etc. So your answer is NO its working how you told it to work.

Java Scanner Breaks when an unknown thing is input

I have a program where a scanner is responding to certain things that you type in.
Here is an example of the code:
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int i=0;
String in = inp.nextLine();
while(i==0){
if(in.equals("x")){
System.out.println("> y");
in = inp.nextLine();
}
}
Everything works fine, like if I type in x, it says y. However, if I type in z, nothing happens, then if I type in x, nothing happens and it completely breaks. What can I do?
You have an infinite loop right so your program is stuck there. Since the second time you enter z which is not equal to x so your code flow doesn't go into the if and get stuck in the infinite loop since your i variable doesn't change either.
You have created infinite loop.
When input is z, check for equalitiy fails and loop keeps spining on condition i == 0 which is always true.
If you want x to continue working after you put in a value that is not accepted take the in = inp.nextLine(); call out like this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
int i=0;
String in = inp.nextLine();
while(i==0){
if(in.equals("x")){
System.out.println("> y");
//in = inp.nextLine(); remove this
}
in = inp.nextLine();
}
}
Not sure if this is what you were looking for.
Also if you do not plan to change i, you can simply keep the while loop going by doing this.
while(true){
//do stuff here
}
Move this line:
in = inp.nextLine();
outside of the curly braces that it is in.
Also, as others have said you have an infinite loop. One way to fix that is have a sentinel character (like 'q') that it checks for and breaks out if it is detected.
Like everyone said, you're in an infinite loop, and when you type z and the equality check fails, you never enter the if block again to check for user input, so typing x again after z won't print anything.
Assuming you want to keep your program as is and continually ask for input, you can just move the:
in = inp.nextLine();
after the if block.
You may want to have some sort of terminating condition though so the program can exit (like you exit the loop when the user types q or something along those lines).
When you enter z, nothing happens because you did not instruct it to do anything if inpout is not equal to x.
Since the in = inp.nextLine(); is in the if condition, it wont read anything from the keyboard if you do not enter x. So move it outside of the loop.
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int i=0;
String in = inp.nextLine();
while(i==0){
if(in.equals("x")){
System.out.println("> y");
}else{
System.out.println("input != x");
}
in = inp.nextLine();
}

Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.
//.....
Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;
String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}
}
This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!
Don't know how to stablish a dynamic string[] length, letting the user establish the string[].length
It is not necessary to do that. But here's how.
Approach #1: ask the user to give you a number and then allocate the array like this:
String[] strings = new String[theNumber];
Warning: the requirements don't say you are allowed to do that, and you may lose marks for deviating from the requirements.
Approach #2: use an ArrayList to accumulate a list of words, the use List.toArray to create an array from the list contents. (Read the javadocs for list to work it out.)
Of course, error here, just did it to put one System.out.print of how should the result be.
Yea. One problem is that the length is 1000, but you don't have 1000 actual strings in the array. The same problem affects your earlier code too. Think about is ...
I'm not going to fix your code to make it work. I've given you enough hints for you to do that for yourself. If you are prepared to put in the effort.
One more hint: you can / should use break to break out of the first loop.
I know some words are not in English but in Catalan, but the code can be perfectly understood, yesterday I finally programmed this answer:
public static void main(String[] args) {
Scanner entrada= new Scanner(System.in);
System.out.println("Escriu les paraules que vulguis, per acabar, usa la paraula 'fi'.");
String paraules = "";
int c=0;
do {
String paraula = entrada.next();
if (paraula.equals("fi")) {
c++;
} else {
if (paraula.compareTo(paraules) > 0) {
paraules = paraula;
}
}
} while (c==0);
System.out.println("L'última parala ordenada alfabèticament és "+paraules+".\n");
}
}

Inifnite loop while reading numbers

Basically I am trying to write a program that will read a finite set of values from the user then print the average. (I know how to do the calculations so I will leave those out.)
I am having a problem with the logic side of the loop.
I understand that everyone here would prefer that I attempted it but I am new to loops and I am having extreme difficulties understanding loop logic.
I am attempting to do this assignment for my class but the teacher is flying through material and does not help at all when questions are asked. When I ask for help with a problem he says do your best to attempt it and I will grade it accordingly?
I honestly do not know where to start.
import java.util.Scanner;
public class P4Point5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String Status = "";
int count = 0;
while (in.hasNext()) {
count++;
}
for (int i = 0; i < count; i++) {
//Do calculations here?
}
}
}
You never get the next element:
while (in.hasNext())
count++;
You are always on the 1st element and asking if there is a 2nd element.
You should use:
while (in.hasNext())
int next = sc.nextInt();
BTW: please avoid statement without curly brackets. It is the root of all evil.
When you read for the first time, you don't read anymore, so hasNext() will stay always true since there will always be next element, which is.. the current element you're reading.
One solution is to do something like that:
String input = null;
while((input = in.next()) != null) {
//...
}
You can try this:
while (in.nextInt() != 'SOME INT TO STOP LOOP')
count++;
Instead of verify every time if we have an entered number, we can verify if the entered number is an stop condition.

Categories

Resources