Nivetha Chezhian Nivetha Chezhian - 3 months ago 5
Java Question

Prompt user to enter integer values for an integer array until he enters something like "stop" or double enter

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Prime {

public static void main (String str[]) throws IOException
{
int arr[]=new int[20];
int a,count=0;
Scanner in=new Scanner(System.in);
for(int i=0;i<arr.length;i++)
{
a=in.nextInt();
if(a!="stop")
{
arr[i]=a;
count++;
}
else
break();

}

for(int j=0;j<count;j++)
{
System.out.println(arr[j]);
}

}

}


I tried to prompt the user to enter integer values for the integer array arr until he types "stop".I assumed that the condition would go true because I learned somewhere that during the condition check "stop" would be converted to int.But I get type mismatch error.Why is it so.Can anyone suggest an alternative way to achieve the same.Thank you

Answer

You can do this way:

String input = null;
int i = 0;

while(in.hasNext()) {        
    input = in.next();     
    if ("stop".equalsIgnoreCase(input))
        break;

    arr[i++] = Integer.parseInt(input);
}

for(int j=0;j<i;j++) {     
    System.out.println(arr[j]);
}