I am using while loop in this programe and it seems that it is not reading the c
ID: 3628121 • Letter: I
Question
I am using while loop in this programe and it seems that it is not reading the code within the while loop. ANy ideas?
import java.util.Arrays;
import java.util.Scanner;
public class MytestArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum =0, average =0, count=1;
char responseChar;
String response;
int[] smallArray = new int[10];
for (int i = 0; i < smallArray.length; i++)
{
System.out.println("Enter a floating numbers: ");
smallArray[i] = scanner.nextInt();
scanner.nextLine(); // to get and discard the nextline token
System.out.println("Do you want to continue? y or n?");
response = scanner.nextLine();
responseChar = response.charAt(0);
while(responseChar =='y');
{
System.out.println("Enter a floating number: ");
smallArray[i] = scanner.nextInt();
scanner.nextLine(); // to get and discard the nextline token
System.out.println("Do you want to continuer? y or n?");
response = scanner.nextLine();
responseChar = response.charAt(0);
count ++;
}
sum += smallArray[i];
average = sum/count;
}
System.out.println("You have entered: ");
System.out.println(Arrays.toString(smallArray));
System.out.println("Your sum is: " +sum);
System.out.println(" Your average is: " +average);
}
}
Explanation / Answer
// code works - run it.
import java.util.Arrays;
import java.util.Scanner;
public class MytestArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float sum = 0.0f, average = 0.0f;
String response;
int i = 0;
float[] smallArray = new float[10];
do
{
System.out.println("Enter a floating number: ");
smallArray[i] = scanner.nextFloat();
scanner.nextLine(); // to get and discard the nextline token
System.out.println("Do you want to continue ? y or n?");
response = scanner.nextLine();
sum += smallArray[i];
i++;
}while(response.equals("y"));
average = sum/i;
System.out.println("You have entered: ");
System.out.println(Arrays.toString(smallArray));
System.out.println("Your sum is: " + sum);
System.out.println(" Your average is: " + average);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.