I am new to java and I would like to store inputted data on an array. My goal is to store the student's grades. So far, this is my code.
import java.util.Scanner;
public class GradesArray {
public static void main (String[]args){
int numStudents = 0;
double grades[]= new double[0];
double gradesStudent;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of students: ");
numStudents = in.nextInt();
for (int i = 1;i<=numStudents;i++){
System.out.print("Enter the grade of student "+i+" : ");
gradesStudent = in.nextInt();
grades[i]=gradesStudent;
}
}
}
so my problem is. I get this error.
`Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GradesArray.main(GradesArray.java:14)`
There are 2 issues here. First:
double grades[]= new double[0];
You have made the array size 0 (new double[0];). However, you ask the user what size you want it to be. So let's declare this variable when you get that first user input:
System.out.println("Enter the number of students: ");
numStudents = in.nextInt();
double grades[]= new double[numStudents];
Second your loop is wrong. Java starts it's indexes for arrays at 0 (not 1). Say you have size N array, then the indexes are 0 to N-1. Change your loop from:
for (int i = 1;i<=numStudents;i++){
//code
}
To:
for (int i = 0;i < numStudents;i++){
//code
}
You are almost there. You are creating an array of length 0 (new double[0]), you must use the inputed value numStudents to create the array:
double grades[] = new double[numStudents]; // You must specify the length inside []
Note that you will have to create the array after you have received the input in
numStudents = in.nextInt();
Also, remember that indexes in Java starts in 0, so your for loop should start with 0 and end in numStudents - 1. In other words i < numStudents:
for (int i = 0; i < numStudents; i++) {
... // modify the necessary
}
First of all, why are you doing this:
double grades[]= new double[0];
↑
This is not the default values of the array, it's its size, you should fix it to be the number of grades you want to store. You are getting the exception because your array can have only 0 elements.
Second, arrays are zero-based in Java. This line
for (int i = 1;i<=numStudents;i++){
Should be
for (int i = 0;i<numStudents;i++){
↑ ↑
The below statement is problematic and it would create an array of 0 elements :
double grades[]= new double[0];
Instead use this :
double grades[]= new double[numStudents];
Please edit your code:
double grades[]= new double[numStudents];
And change the for command to this
for (int i = 1;i < numStudents;i++){
}
loop was outofbound
Compare with your code:
int numStudents = 0;
double gradesStudent;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of students: ");
numStudents = in.nextInt();
double grades[]= new double[numStudents];
for (int i = 0;i<=numStudents-1;i++){
System.out.print("Enter the grade of student "+(i+1)+" : ");
gradesStudent = in.nextInt();
grades[i]=gradesStudent;
}
}
Related
This question already has answers here:
For-each Loop in Java
(3 answers)
Initializing an array in Java using the 'advanced' for each loop [duplicate]
(5 answers)
Closed 5 years ago.
import java.util.Scanner;
import java.util.Arrays;
public class Sort_Array {
public static void main(String[] args) {
int a;
Scanner sc = new Scanner(System.in);
System.out.println(" Enter size of Array ");
int n = sc.nextInt();
int[] arr_num = new int[n];
System.out.println(" Enter the integers in the Array");
for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}
System.out.println(" Array before sorting ----\n");
for(int j : arr_num)
{
System.out.print(j+",");
}
System.out.println("\n");
Arrays.sort(arr_num);
System.out.println(" Array after sorting ----\n");
for(int k : arr_num)
{
System.out.print(k+",");
}
}
}
Output
Enter size of Array
2
Enter the integers in the Array
5
6
Array before sorting ----
6,0,
Array after sorting ----
0,6,
Change this:
for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}
To a traditional for-loop and it should work.
for (int i = 0; i < arr_num.length; i++) {
arr_num[i] = sc.nextInt();
}
You never initialize your array arr_num, so it will be full of zeros
int[] arr_num = new int[n];
....
for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}
Will then become:
// Pseudocode
for(int i : {0, 0, ... , 0} )
{
arr_num[i] = sc.nextInt();
}
So you will always write to arr_num[0]
You probably want to have this instead:
for(int i = 0; i < arr_num.length; i++)
{
arr_num[i] = sc.nextInt();
}
You are entering elements of array through foreach loop, but the correct way is:
System.out.println(" Enter the integers in the Array");
/*for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}*/
for(int i=0;i<n;i++){
arr_num[i] = sc.nextInt();
}
System.out.println(" Enter size of Array ");
int n = sc.nextInt();
int[] arr_num = new int[n];
Here you see what is really happening when you have passed the size of the array say, 2
arr_num is getting initialized with 0 value ( which is the default value for int object)
0 0
After this, you have used the for each loop.
Which basically says, When you see the colon (:) read it as “in.” So basically, you are reading each int i in array_num which are 0 0.
for(int i : arr_num)
{
arr_num[i] = sc.nextInt(); //arr_num[0] = sc.nextInt();
//again, arr_num[0] = sc.nextInt();
}
So this is the reason you are getting
6,0
because 5 which was inputted by you is now replaced by 6 again at arr_num[0]. while 2nd 0 still stays which is at arr_num[1].
As other answers suggest, use a different loop. And read more about for each loop.
Beginner Java programmer here. I am trying to make a program that asks the user how many grades they would like to enter. Then, I want to store the grades the user entered into an array. Finally, I want to find the mean of the grades entered and print out a list of every grade below the mean. As of now, my code calculates the mean of the grades that the user enters but I cannot figure out how to print the grades below the mean. I believe the problem lies in my last for loop but I cannot figure out how to fix it. Also, did I implement the array correctly? Thanks to every who took the time to help me!
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
// user enters # of grades they requested to enter
for (int counter = 0; counter < q; counter++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
double[] scores = new double[] {grades};
// adds up all elements (grades)
for (int k = 0; k < scores.length; k++) {
total += scores[k]; //sums up entered grades
}
}
total = total / q; //calcs mean
//loops prints grades less than mean
for (grades = 0; grades < total; grades++){
System.out.println(grades);
}
}
public static void grades(){
Scanner in = new Scanner(System.in);
System.out.println("How many grades would you like to enter? "); //user input how many grades user would like to enter
int q = in.nextInt();
double[] grades = new double[q];
double sum = 0;
for (int counter = 0; counter < q; counter++){ //user enters # of grades they requested to enter
System.out.println("Enter your grades: ");
double grade = in.nextInt();
grades[counter] = grade;
sum += grade;
}
double mean = sum / q;
System.out.println("Mean: " + mean);
for (int i = 0; i < q; i++){ //loops prints grades less than mean
if (grades[i] < mean) {
System.out.println(grades[i]);
}
}
}
Your last loop makes no sense
You should be counting through ALL the items in the array and then doing an IF to test if it's below the mean and then printing it if it is below the mean
You have made the loop iterate from 0 up to the mean.. that just makes no sense it's like saying the mean score among a group of students was 30% now print all the grades from student0 to student30 That makes no sense to do that. You should be interested in student 31 and student 32.. dont' stop at student number 30. student1 might have a grade above the mean and student 40 may have a grade below the mean. you're mixing up the student number(the index of the location in the array) with the grade.
ADDED
You are actually doing even worse than that..because grades isn't even an array it is a variable with one number in it. You have an array that increments a variable and prints the variable like printing 1,2,3,4,5
You're meant to do a loop i=1 to n, and print array[i]
You are doing a loop i=1 to n and you are printing i
You should figure out what an array is all about rather than worrying about calculating a mean. Make your own simpler exercises testing what you do/don't understand rather than something out of a book or something the teacher gave you. And use your explorations to understand this exercise your teacher/book gave you.
Your code had some issues. First off your array was being initialized with every iteration for a new grade being entered, which would result in one index since the previous inputs were overriding it. The array scores should be initialized outside the for loop.
Also, your for loop for printing out the grades wasn't correct. You needed to iterate over the scores array and print out each individual value.
The code below works and demonstrates where you went wrong:
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
double[] scores = new double[q];//initialize here
// user enters # of grades they requested to enter
for (int i = 0; i < scores.length; i++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
scores[i] = grades;//append values to each index
// adds up all elements (grades)
total += scores[i]; //sums up entered grades
}
total = total / q; //calcs mean
System.out.println("Mean: " + total);
//iterate through the scores array with filled values
for (int i = 0; i < scores.length; i++) {
System.out.println("Grade #" + i + ": " + scores[i]);
}
}
what might be the problem of that .. the total and average is wrong.
import java.io.*;
class overloading2
{
String name;
int year;
String section;
String subject[];
double grade[];
double average;
public void enrolSubjects()throws Exception
{
DataInputStream mat=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 subject:");
subject=new String[3];
for(int sub=0;sub<3;sub++)
{
subject[2]=(mat.readLine());
}
}
catch(IOException ioe)
{
}
}
public double enterGrades(double grade1,double grade2,double grade3)
{
DataInputStream math=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 grades:");
grade=new double[3];
for(int x=0; x<3; x++)
{
grade[2]=Double.parseDouble(math.readLine());
}
}
catch(IOException ioe)
{
}
return enterGrades();
}
double enterGrades()
{
double total=0.0;
for(int x=0; x<3; x++)
{
total+=grade[2];
average=total/3;
}
return average;
}
public static void main(String []args)throws Exception
{
overloading2 ostud1=new overloading2();
double a=0.0,b=0.0,c=0.0;
ostud1.enrolSubjects();
ostud1.enterGrades(a,b,c);
System.out.println("average grade is "+ostud1.enterGrades());
}
}
I have to save 10 numbers entered by a user into an array using a for loop. After that, I have to use an enhanced for loop to find the largest and smallest values in the array. I don't know how to save numbers in an array. I also have problems finding the smallest and largest values from the array and displaying them. I got an error on the for loop section where I set highestvalue and lowestvalue=inputnumber.
Here is my code:
import java.util.Scanner;
public class ArrayTester
{
public static void main(String[] args)
{
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[inputNumber] = inputNumber;
//for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
//{
//largestNumber=inputNumber;
//smallestNumber=inputNumber;
//}
}
System.out.printf("%s%8s\n", "index", "value");
System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
}
}
Replace
number[inputNumber] = inputNumber;
with
number[counter] = inputNumber;
and thats it. As for finding mix and max, use Collections.sort() on your array. First element will be min, and the last max.
Change
number[inputNumber] = inputNumber;
to
number[counter] = inputNumber;
You want to add each new number to the counter position of the array.
As for finding the minimum, maximum. The same loop that reads the inputs into the array can do that. Initialize largestNumber to Integer.MIN_VALUE and smallestNumber to Integer.MAX_VALUE. Then, each time you get a new number, compare it to both largestNumber and smallestNumber, and update them if the new number is higher/lower respectively.
assuming that you don't have to store the numbers in the same order in which they were entered by the user, you would make a sorted insert. that means, for each value entered, find the index at which this number can be inserted while maintaining a sorted array (if there exists a number at this index you have to move it move it to the right)
provided a sorted array you can find min and max in O(1):
min = number[0];
max = number[n-1];
make the following changes
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber ;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[counter] = inputNumber;
// for loop that will check for largest and smallest no
}
smallestNumber = number[0];
largestNumber = number[0];
for(int i=1; i< number.length; i++)
{
if(number[i] > largestNumber)
largestNumber = number[i];
else if (number[i] < smallestNumber)
smallestNumber = number[i];
}
// System.out.printf("%s%8s\n", "index", "value");
// System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
Also: you cannot use a for loop in this way
for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
this is a conditional case not a loop
I would suggest you to try out this one.Let me know if it works.:-
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int num[]=new int[10];
int max=0,min=0;
for(int i=0;i<10;i++){
System.out.println("Enter number:-");
num[i]=in.nextInt();
if(num[i]>=max)
max=num[i];
if(num[i]<=min)
min=num[i];
}
min=num[0];
for(int i=0;i<10;i++){
if(num[i]<=min)
min=num[i];
}
System.out.println("The array elements are:-");
for(int i=0;i<10;i++)
System.out.print(num[i]+" ");
System.out.println();
System.out.println("Largest is:-"+max+" "+"Smallest is:"+min);
}
}
I'm trying to create a code that lets the user determine the size and elements of an array and then print it out. So far I have this.
import java.util.Scanner;
public class test3 {
public static void main (String[] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
System.out.println(values[i]);
}
}
}
I don't know if it is right because when a user inputs the size and then the elements, the code is just displaying the element as the user inputs it. For example,
input how many numbers you want to find the median for
5
please enter 5 numbers
3//user input
3//what is displayed.
I want to make it so that the user inputs all of their numbers and THEN it displays the inputed numbers as an array.
We are not allowed to use the array class by the way.
import java.util.Scanner;
public class test3 {
public static void main (String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
}
for (int i = 0; i < num; i++) {
System.out.println(values[i]);
}
}
}
Your for loop will execute for as many number as the user has entered, in your test case 5. Every iteration will take a number from the keyboard input, place it into the array and display it. Since you want to capture all the numbers first and then want to display them you should remove
System.out.println(values[i]);
from the for loop and place that into another for loop to display the numbers like so
for(int x=0 ;i < num ; i++)
{
System.out.println(values[x]);
}
This way the first loop will gather all the numbers and after the numbers are collected the second loop will display the numbers one by one iterating over the array.
Hope this helps!
I don't understand why this is going out of bounds, can you help me?
What should happen:
user inputs length of list
user inputs all items in the list, only prompted until the user-inputed length of list (a) is reached.
For some reason after the first item in the list it goes out of bounds but I can't tell why.
import java.util.Scanner; //import scanner
public class project2 {
public static void main (String[] args){
Scanner input = new Scanner(System.in); //scanner for input
int a = 0;
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
System.out.println("How long are the lists? ");
System.out.print("(The lists should be the same length): ");
a = input.nextInt();
int count=1;
System.out.println("Enter numbers for list A:");
for(int j = 0; j < a-1 ; j++){ //user input numbers loop into array "list"
System.out.print(count + ": ");
lista[j] = input.nextDouble();
count++;
}
}
}
When you declare your lista and listb arrays, you use a as the length, but at that time, it's 0. You haven't assigned the user's value to a yet.
Create your arrays after you have the length from the input.
a = input.nextInt();
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
you created array with 0 element and if you enter any number for a which is greater than 1 it will attempt to look at index 1 which is out of bound