Handling out of bounds on a fixed array - java

My problem is that for example there's only three passing grades, the user entered then the size of passGrade array would only be three, same with failGrade: if the user entered two failing grades then the size of failGrade array would only be two, in short I want the two arrays to be of fixed lengths. In my program it goes out of bounds.
Here's the piece of code I'm referring to:
Scanner input=new Scanner(System.in);
int gradeSize=0;
int fixedPassed=0;
int fixedFail=0;
int grades[]=new int[gradeSize];
int passGrade[]=new int[fixedPassed];
int failGrade[]=new int[fixedFail];
System.out.print("Enter Grade Size: ");
gradeSize=input.nextInt();
System.out.println();
System.out.print("Enter Grades: ");
for(int i=0; i<gradeSize; i++)
{
grades[i]=input.nextInt();
while(grades[i]<1 || grades[i]>100)
{
grades[i]=input.nextInt();
}
if(grades[i]>=75)
{
fixedPassed++;
passGrade[i]=grades[i];
}
else if(grades[i]<75)
{
fixedFail++;
failGrade[i]=grades[i];
}
}
for(int i=0; i<fixedPassed; i++)
{
System.out.print(passGrade[i]+" ");
}
for(int i=0; i<fixedFail; i++)
{
System.out.print(failGrade[i]+" ");
}

Java arrays are fixed size. So you need to get the input, then count the pass/fails. Then create your pass fail arrays and then copy the grades into them. You could do something like this,
System.out.print("Enter Grade Size: ");
int gradeSize = input.nextInt();
int passCount = 0;
int grades[]=new int[gradeSize];
System.out.println();
System.out.print("Enter Grades: ");
for (int i = 0; i < gradeSize; i++) {
grades[i] = input.nextInt();
if(grades[i] >= 75) {
passCount++;
}
}
int passGrade[] = new int[passCount];
int failGrade[] = new int[grades.length - passCount];
int failCount = passCount = 0;
for (int grade : grades) {
if (grade >= 75) {
passGrade[passCount++] = grade;
} else {
failGrade[failCount++] = grade;
}
}
System.out.println("Passing Grades: " + Arrays.toString(passGrade));
System.out.println("Failing Grades: " + Arrays.toString(failGrade));

Since you don't know in advance the length of the input, and you don't know in advance how many passed and how many failed, you can't create the arrays before first processing the input.
You should use 3 collections (HashSet, ArrayList, etc ...) to store the input grades, passed grades and failed grades. Once you are done, you can initialize your 3 arrays based on the size() of the collections, and then iterate over the collections to copy their contents to the arrays.

Related

The task is to write a java program to test if an array contains a specific value in java

I got confused and didn't know what to add or change the loops.
Can someone please help me and tell me what I should do in order to run my code? It would be a big help to me. I'm only a beginner in Java...
**here's my code: **
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
x = input.nextInt();
num[i]=x;
if ( num [i] == x );
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
if ( num[i] == search){
System.out.println (search + " is found in the array!");
}
else{
System.out.println ("Your number is not in the array.");
}
}
}
The sample output of my task is (using scanner):
Input the size of the array: 4
Enter the values:
14
15
16
17
Enter the search value: 14
14 is found in your input array.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
// System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
System.out.println("Enter Number to add at index "+i+" : ");
x = input.nextInt();
num[i]=x;
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean condition=false;
for(i=0; i < num.length; i++){
if ( num[i] == search){
condition=true;
break;
}
}
if(condition==true){
System.out.println("Number is Array!");
}
else{
System.out.println("Number is not in array");
}
}
your code is to be like this
there is logical error's in your code
to find an element you must traverse through array which can be achieved using loop so the last if else statement in your code must be in a loop
as due to the post increment in first loop after the completion of loop the value of i is one greater than last index of array so in if else statement at if ( num[i] == search) index is not found in array due to which it generates error.
for example I enter array size 3 and at num[0] I enter 1 at num[1] I enter 2 and at num[2] I enter 3 after the loop finishes the value of i become 3 when it come to conditional statement (if else) so it become if(num[3] == search ) but 3 index is not present in array so it generates error.
You need a loop to compare each element of the array with the search value.
boolean found = false;
for (int x : num)
if (x == search) {
found = true;
break;
}
System.out.println(found ? search + " is found in the array!" : "Your number is not in the array.");
Alternatively, with streams:
System.out.println(Arrays.stream(num).anyMatch(x -> x == search) ?
search + " is found in the array!" : "Your number is not in the array.");
Scanner input = new Scanner (System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for (i = 0; i < num.length; i++)
{
x = input.nextInt();
num[i] = x;
if (num[i] == x);
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean flag=false;
for( i=0;i<num.length;i++)
{
if (num[i] == search) {
flag = true;
System.out.println(num[i]+" is found in your input array");
break;
}
}
if (flag==false)
{
System.out.println("Your number is not in the array.");
}
}
[Screenshot][1]

Else statement not printing, wondering if I am calling from setter method incorrectly in java

I'm trying to make a program in java which creates an array. I am trying to have OOP approach. I've made a class file which contains a setter method and my array:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
The elements of the array is taken from the user in my main method:
//Menu loop
int myMonths[] = new int[5];
int index = 0;
int num;
while(choice !=6){
switch (choice){
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
System.out.println("How many months was your project?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//if months is lesser than 2/greater than 12
if((a < 2) || (a > 12)){
System.out.println("Please enter an amount between 2 and 12 months");}
//if months is between 2 and 12 add it to the array
else{myMonths[index++] = a;}
}
calc.setMyMonths(myMonths); //creating the object
break;
I am trying to create a function which displays all the elements of the array. If the array is empty I want it to display a message stating this. However, my else statement will not run. I am trying to figure out why this is & am I calling the array incorrectly? Please see my code below:
case 2:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
Any help would be great! Thanks in advance
Your code :
for(int i=0; i < myMonths.length; i++){
if(myMonths.length != 0){ //if the array is not empty display all items
System.out.println(myMonths[i] + " ");
}
else{System.out.println("No values entered");} //if array is empty display this message
}
if myMonths.length > 0 then it will check for length !!
your code should be:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
UPDATE:
before you create your Array .. Ask the User for Size,
then you can check if empty or not
System.out.println("inter the size:");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] arr = new int[size];
if (arr.length > 0) {
// do your loop
System.out.println("Not Empty");
} else {
// Empty array
System.out.println("Empty");
}

i wrote a code using array and methods to display numbers from the smallest o the largest numbers

i wrote a code using array and method that allow the user to enter any number of numbers and
display the numbers sorted from the smallest number to the largest number however the program works but it doesn't show the numbers here is the code that i wrote
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers you want to enter? ");
int size = s.nextInt();
int i;
double[] numbers1 = new double[size];
System.out.println("Enter " + numbers1.length + " numbers: ");
getNumbers(numbers1);
double[] numbers2 = new double[numbers1.length];
for (i = 0; i < numbers1.length; i++) {
numbers2[i] = numbers1[i];
}
displayNumbers(numbers1);
System.out.println("The numbers after sorting are: ");
sortNumbers(numbers2);
displayNumbers(numbers2);
}
public static void getNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
}
}
public static void sortNumbers(double[] numbers) {
double temp;
double pass;
for (pass = 0; pass < numbers.length; pass++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
public static void displayNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
System.out.print(numbers + " ");
}
System.out.println();
}
}
Your displayNumbers() method is wrong. In the loop you wrote:
numbers[i] = s.nextDouble();
System.out.print(numbers + " " );
You're trying to read again 4 doubles (everytime you call that method) and you're printing the whole array (which doesn't do what you'd expect). What you probably want is this:
System.out.print(numbers[i] + " " );
Your code is inefficient and unclear.
You don't need to create a new Scanner everytime and also why instead of println the array with Arrays.toString(double[]).
You should also make more cleaner instructions and variable names.
Here is an example of how the code should be
public static void main(String[] args)
{
//create a new Scanner with a name that defines it
Scanner scanner = new Scanner(System.in);
//print your instructions
System.out.println("How many numbers would you like to sort?");
//print "> " to let the user to know he should be entering values
System.out.print("> ");
//read the number the user has entered which we will define as how many numbers he would enter next
int totalNumbers = scanner.nextInt();
//create a new array the size of the total numbers
double[] unsortedNumbers = new double[totalNumbers];
//tell the user to enter his unsorted numbers
System.out.println("Enter your unsorted numbers: ");
//loop totalNumbers times until the whole unsortedNumbers is full
for(int index = 0; index < totalNumbers; index++)
{
System.out.print("> ");
unsortedNumbers[index] = scanner.nextDouble();
}
//Print the numbers he entered
System.out.println("You entered: ");
//Arrays.toString prints the array in format [number, number, ...]
System.out.println(Arrays.toString(unsortedNumbers));
//sort the arrays with Arrays.sort which sorts in ascending numerical order
Arrays.sort(unsortedNumbers);
//Print the final result - sorted numbers
System.out.println("Sorted: " + Arrays.toString(unsortedNumbers));
}

Can I do a for loop after two consecutive if statements? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I am working on a program that has to check for certain conditions (and give out an error message if they are not executed) before executing two for loops (one for the sum of grades entered and one for highest and lowest grades)and I'm not sure how to sequence them.
Also my code is getting me this error -->Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 and I'm not sure what to do to fix the error
If anyone can help me with the skeletons of the correct sequence I would truly appreciate it!
Here is my code (I know it looks crazy, sorry I'm learning!):
import java.util.Scanner;
public class Homework {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int numberOfMarks, average, sum, total, mark;
numberOfMarks = 0;
int [] marks = new int[numberOfMarks];
int smallest, largest;
//System.out.println("Enter number of marks: ");
numberOfMarks = input.nextInt();
if(numberOfMarks<0) {
System.out.println("Number of marks must be greater than 0!!");
}
//System.out.println("Enter "+numberOfMarks+"marks: ");
mark = input.nextInt();
if(mark<0) {
System.out.println("Negative marks not allowed!!!");
} else if(mark>100) {
System.out.println("Marks above 100% not allowed!!!");
}
sum = 0;
for(int i = 0; i < marks.length; i++) {
sum += marks[i];
}
smallest=marks[0];
largest=marks[0];
for(int i=1;i<marks.length;i++) {
if(marks[i]>largest) {
largest=marks[i];
} else if(marks[i]<smallest) {
smallest=marks[i];
}
average = sum/numberOfMarks;
System.out.println("Highest Mark = "+largest);
System.out.println("Lowest Mark = "+smallest);
System.out.println("Average = "+average);
}
}
}
You can try this:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int numberOfSubjects, sum;
numberOfSubjects = 0;
System.out.print("Enter the total number of subjects: ");
numberOfSubjects = in.nextInt();
if(numberOfSubjects < 0){
System.out.println("Number of marks must be greater than 0!!");
}
else {
int []marks = new int[numberOfSubjects];
sum = 0;
System.out.print("Enter the marks: ");
// add condition inside for loop for marks not less than 1 or greater than 100
for(int i=0; i<marks.length; i++) {
marks[i] = in.nextInt();
}
// calculate total
for(int i = 0; i < marks.length; i++){
sum += marks[i];
}
// sort marks
Arrays.sort(marks);
System.out.println("Total: " + sum);
System.out.println("Average: " + sum/numberOfSubjects);
System.out.println("Minimum: " + marks[0]);
System.out.println("Maximum: " + marks[marks.length-1]);
}
}
}
Code flow should look like this. Even you can add condition of marks(not less than 1 or greater than 100) while reading marks.
Problem is in the logic, see comments bellow
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfMarks, average, sum, total, mark;
numberOfMarks = 0;
/*there you are creating empty array
you told marks should have length of value numberOfMarks, but
numberOfMarks is equal to zero at this time
*/
int[] marks = new int[numberOfMarks];
int smallest, largest;
//System.out.println("Enter number of marks: ");
numberOfMarks = input.nextInt();
/*
not interesting conditions checking...
*/
for (int i = 0; i < marks.length; i++) {
/*
There you are trying to access 1st element of marks
- indexing from zero, as usual
But there is no first element, array has zero length, zero elements
Ok, you told array should have length of numberOfMarks, but it was
when value was zero, so if you will change numberOfMarks later, it
has no impact on the length of array
*/
sum += marks[i];
}
/*
stats computing, not important
*/
}
}
So, once you got user input for number of marks, then you can "recreate" - realloc / redefine the array, as before
marks = new int[numberOfMarks];
In your case bellow
//System.out.println("Enter number of marks: ");
numberOfMarks = input.nextInt();
Using variable in length of array does not means it will be bounded, so if variable in array length (in this case numberOfMarks) will change later after usage, then length of array will be still the same

How to work around java workspace and change to double

so I have to write a program that asks the user to enter in the number of students, then asks to input name of first student and then asks the grade of the student, then it goes on to the next student. For example it asks how many students and I say 5, then it asks me the name of the first student, and I say bob smith, then it asks me the grade, so I say 12.5, then it asks me the next students name and so on till I finish all five students. It then sorts everyone in descending order by their grade. I have it working, but there are two problems. 1.I cant put in a first and last name because of the white space. It works fine if I put in bob but not when I put bob smith. 2. I cant get it to read in double variables for the grade, only int. so 5 works but not 5.3.Here is my code:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
String[] names = new String[numofstudents];
int[] array = new int[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] = input.next();
System.out.print("Enter the student's score: ");
array[i] = input.nextInt();
}
selectionSort(names, array);
System.out.println(Arrays.toString(names));
}
public static void selectionSort(String[] names, int[] array) {
for(int i = array.length - 1; i >= 1; i--) {
String temp;
int currentMax = array[0];
int currentMaxIndex = 0;
for(int j = 1; j <= i; j++) {
if (currentMax > array[j]) {
currentMax = array[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
}
}
Use Scanner.nextDouble() instead of nextInt().
For your name problem set the delimiter to end of line
input.useDelimiter("\\n");
And for the grades issue you need to make array variable an array of floats or doubles and then use input.nextFloat() or input.nextDouble().
See: http://ideone.com/Qz7hD8

Categories

Resources