Why get ArrayIndexOutOfBound Exception? - java

Modify the program below:
public class LenghtArray {
public static void main(String[] args) {
int[] ages = {16, 19, 30, 60, 21, 25, 2, 13};
// Print all elements
for (int count = 0; count < ages.length; count++) {
System.out.print(ages[count] + " ");
}
// Sum of all ages
System.out.println(" ");
int total = 0;
for (int count = 0; count < ages.length; count++) {
total = total + ages[count];
}
System.out.print("Total :" + total + " ");
}
}
Here down is my expected output:
Input length of an array: 4
age[0]: 65
age[1]: 10
age[2]: 60
age[3]: 18
Display all elements in an array: 65, 10, 60, 18
Total: 153
So far here's what I have, I don't know what's wrong with it. My professor said you just need to add 2 string of lines. I keep on adding more
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int[] ages = {0};
System.out.println("Input length of an array:");
int number = inp.nextInt();
for (int count = 0; count < number; count++) {
System.out.println("age[" + count + "]: ");
ages[count] = inp.nextInt();
}
// Print all elements
for (int count = 0; count < ages.length; count++) {
System.out.print(ages[count] + " ");
}
// Sum of all ages
System.out.println(" ");
int total = 0;
for (int count = 0; count < ages.length; count++) {
total = total + ages[count];
}
System.out.print("Total :" + total + " ");
}

I would recommend first of all making decomposition of the task into smaller element steps. Then implement each step and check the result. In this case, you can easier find a bug in the program.
P.S. Your teacher could give a + sign seeing this
public class LengthArray {
public static void main(String... args) {
int[] ages = createArray();
printArray(ages);
printTotal(ages);
}
private static int[] createArray() {
Scanner scan = new Scanner(System.in);
System.out.print("Input length of an array: ");
int[] ages = new int[scan.nextInt()];
for (int i = 0; i < ages.length; i++) {
System.out.format("age[%d]: ", i);
ages[i] = scan.nextInt();
}
return ages;
}
private static void printArray(int... ages) {
System.out.println("Display all elements in an array: " + Arrays.toString(ages));
}
private static void printTotal(int... ages) {
System.out.println("Total: " + calcTotal(ages));
}
private static int calcTotal(int... ages) {
int total = 0;
for (int age : ages)
total += age;
return total;
}
}
Output:
Input length of an array: 4
age[0]: 65
age[1]: 10
age[2]: 60
age[3]: 18
Display all elements in an array: [65, 10, 60, 18]
Total: 153

You need to change place and style of the declaration and creation of the age array:
declare it after you know it's desired length
create it with the desired length:
int number = inp.nextInt();
int[] ages = new int[number];
Rest of your code looks good. You might want to improve it a bit by printing the texts before the inputs (like "Input length of an array:") only with System.out.print instead of System.out.println - this will make the input on the same row as the text before.
In contrary you should use the println for the total output.

Related

Setting a number in range in arrays for java

While writing a code for printing out random numbers ranging from 0 to 99, I had faced some difficulties. I tried to change the condition in the for statement to e<100, however, it had occurred an error. Where should I put the conditions in order for my output to show numbers between 0 to 99?
public class EvensOdds {
public static void printArray(int[] ear) {
System.out.println("ODD NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 10);
if(ear[e]%2!=0)
System.out.print(ear[e] + " ");
}
System.out.println("\n" + "EVEN NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 10);
if(ear[e]%2==0)
System.out.print(ear[e] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] numberArray = new int[25];
printArray(numberArray);
}
}
In Java 8, below creates an array with size 25, with random entries between 0,99
Random random = new Random();
int[] array = random.ints(25, 0, 100).toArray();

How do i find max and min of an nested ArrayList?

Let's say i have N ArrayLists and inside them, there are M other ArrayLists, so i'm trying to find the min and max of each of these M ArrayLists, what's the best way to do that?
ArrayList<String> myname = new ArrayList<String>(n);
ArrayList<Integer> myscore = new ArrayList<Integer>(m);
for (int i = 0; i < n; i++) {
System.out.println("enter name of contestant");
myname.add(input.next());
for (int j = 0; j < m; j++) {
System.out.println("enter score");
myscore.add(input.nextInt());
}
You can use IntSummaryStatistics class:
IntSummaryStatistics istats = IntStream.of(1,22,33,44,55).
collect(IntSummaryStatistics::new, IntSummaryStatistics::accept,
IntSummaryStatistics::combine);
System.out.println("Max: "+istats.getMax()+", Min: "+istats.getMin());
// Max: 55, Min: 1
Your question is not that much explanatory. Lets say that you want to add the names of some student and you also want to save the corresponding marks obtained by each student. So you will need three ArrayList reference variable. First one is for storing the names, second one is for storing the marks obtained by the student, and the third one is for storing the ArrayList of marks obtained by a single student. Here goes the code
package exmaple;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Finder {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int n = userInput.nextInt();
int m = userInput.nextInt();
ArrayList<String> names = new ArrayList<String>(n);
ArrayList<Integer> numbers;
ArrayList<ArrayList<Integer>> holderOfMarksArayList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i<n; i++) {
System.out.println("Enter name of contentant.");
String name = userInput.next();
names.add(name);
numbers = new ArrayList<Integer>(m);
for(int j = 0; j<m; j++) {
System.out.println("Enter score.");
numbers.add(userInput.nextInt());
}
holderOfMarksArayList.add(numbers);
}
int counter = 0;
for(String name : names) {
numbers = holderOfMarksArayList.get(counter);
Collections.sort(numbers);
int maxScore = numbers.get(numbers.size() - 1);
int minScore = numbers.get(0);
System.out.println(name +", Max Score = " + maxScore + " Min Score = " + minScore);
counter++;
}
userInput.close();
}
}
If you try with the following input
AAA = 20, 80, 10
XXX = 66, 98, 96
YYY = 65, 12, 76
You will get the following output
AAA, Max Score = 80 Min Score = 10
XXX, Max Score = 98 Min Score = 66
YYY, Max Score = 76 Min Score = 12
You can use Collections.max(arrayList). Just to illustrate how it works.
public static void main(String[] args)
{
ArrayList<ArrayList<Integer>> n = new ArrayList<>();
ArrayList<Integer> m0 = new ArrayList<>();
ArrayList<Integer> m1 = new ArrayList<>();
m0.add(100);
m0.add(200);
m0.add(300);
m0.add(400);
n.add(m0);
m1.add(10);
m1.add(20);
m1.add(30);
m1.add(40);
n.add(m1);
System.out.println(n);
System.out.println(Collections.max(n.get(0)));
System.out.println(Collections.min(n.get(0)));
System.out.println(Collections.max(n.get(1)));
System.out.println(Collections.min(n.get(1)));
}
RUN
[[100, 200, 300, 400], [10, 20, 30, 40]]
400
100
40
10
For your case, you can loop through your n arraylists to get the min and max of each of them.
If you want to find out the winner you should sum the marks obtained by each winner and compare it with a temp variable. if the sum is greater then the temp then assign the sum to the temp. the last value assigned in the temp will be highest mark obtained. After the first for loop the code will be like that.
String winnerName = "";
int temp = 0;
int counter = 0;
for(String name : names) {
numbers = holderOfMarksArayList.get(counter);
int sum = 0;
for( int number : numbers ) {
sum += number;
}
if( sum > temp ) {
temp = sum;
winnerName = name;
}
Collections.sort(numbers);
int maxScore = numbers.get(numbers.size() - 1);
int minScore = numbers.get(0);
System.out.println(name +", Max Score = " + maxScore + " Min Score = " + minScore +" Sum " + sum);
counter++;
}
System.out.println("Winner " + winnerName + " Total "+ temp);

Display number of values over a certain percentage Java

I need to write a Java program using a bi-dimensional array that stores marks achieved by 40 students in 8 subjects, finds the average and also finds the occurrences in which a distinction was obtained (a mark over 70%).
The program works fine except for the last requirement. Right now it's counting all marks if one or more are over 70% (therefore the result is always 8).
I guess I am confused on how to get a count of the marks above 70% only. Sample code is fine but please also try to explain what I am doing wrong...
Thank you! :)
import java.util.Scanner;
public class db {
public static void main(String[] args) {
//Variables
double mark = 0, average = 0, sum = 0, counter = 0, achievement = 0, percentage = 0, counterpercentage = 0;
double[][] marksTable = new double[40][8];
//New Scanner object
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 40; studentNo++) {
System.out.println("Enter marks for student no" + studentNo);
sum = 0;
counter = 0;
for (int moduleNo = 0; moduleNo < 8; moduleNo++) {
System.out.println("Mark for student " + studentNo + " for module no " + moduleNo + ":");
//Read value into variable mark
mark = fromKeyboard.nextDouble();
// Write mark into array
marksTable[studentNo][moduleNo] = mark;
//Calculations
sum = sum + mark;
counter = counter + 1;
}
percentage = mark;
average = sum / counter;
counterpercentage = counter;
//Display array
for (int moduleNo = 0; moduleNo < 8; moduleNo++) {
System.out.println("Average for student " + studentNo + " for module no " + moduleNo + " is: " + average);
break;
}
if (percentage >= 70) {
System.out.println(" The number of high marks achieved for this student are: " + counterpercentage);
}
if (percentage < 70) {
System.out.println("No high marks obtained");
}
}
}
}
Try this:
import java.util.Scanner;
public class db
{
public static void main (String []args)
{
//Variables
double mark=0, average=0, sum=0, counter=0, achievement=0, percentage=0, counterpercentage=0;
double[][] marksTable = new double[40][8];
//New Scanner object
Scanner fromKeyboard=new Scanner (System.in);
for (int studentNo = 0; studentNo < 40; studentNo++)
{
System.out.println("Enter marks for student no" +studentNo);
sum =0 ;
counter = 0;
for (int moduleNo = 0; moduleNo < 8; moduleNo++)
{
System.out.println("Mark for student "+studentNo+" for module no "+moduleNo+":");
//Read value into variable mark
mark = fromKeyboard.nextDouble();
// Write mark into array
marksTable[studentNo][moduleNo] = mark;
//Calculations
sum=sum+mark;
counter=counter+1;
if(mark >= 70) { //***Changed***//
counterpercentage++;
}
}
average=sum/counter;
//Display array
for (int moduleNo = 0; moduleNo < 8; moduleNo++)
{
System.out.println("Average for student "+studentNo+" for module no "+moduleNo+" is: "+average);
break;
}
if (counterpercentage >=0) //***Changed***//
{
System.out.println("The number of high marks achieved for this student are: "+ counterpercentage);
}
else
{
System.out.println("No high marks obtained");
}
}
}
}
It's because of this statement:
percentage = mark;
It assigns the value of mark to percentage, what we need to do here is to calculate the percentage, which would be total marks divided by max marks e.g.
percentage = (sum/(100.0 * marksTable[studentNo].length))*100; //(Assuming 100 as max marks for eah module)

An array that will declare 5 random numbers from 0 to 100. Then it will average all the numbers that are over 70

This is the homework question that I need to answer.
Write a complete program that declares an array of any five integers, from 0 to 100 , and averages only those integers which are greater than 70 .
Here is my code I have written so far.
import java.util.Random;
public class TestLoop{
public static void main(String[] args){
Random Rnum = new Random();
int[] ar1 = new int[100];
for(int i = 0; i < 5; i++) {
ar1[i] = Rnum.nextInt(100);
System.out.print(ar1[i] + " ");
if(ar1[i] > 70)
System.out.print(ar1[i] + " ");
}
}
}
This allows me to get my five random numbers, but I can't seem to figure out how to average the ones that will be over 70. The last few lines of code are my attempt to isolate the numebrs that are over 70 from the others are not.
try this:
public static void main(String[] args){
Random Rnum = new Random();
int[] ar1 = new int[100];
int counter=0;
double total=0;
for(int i = 0; i < 5; i++) {
ar1[i] = Rnum.nextInt(100);
System.out.print(ar1[i] + " ");
if(ar1[i] > 70)
{
total+=ar1[i];
counter++;
System.out.print(ar1[i] + " ");
}
}
if(counter>0)
{
double average=total/counter;
System.out.println("average="+average);
}
}
You could simply keep track of how many numbers there are above 70 and what the sum of them is.
public static void main(String[] args){
Random Rnum = new Random();
//added variables
int count = 0;
int average = 0;
int[] ar1 = new int[100];
for(int i = 0; i < 5; i++) {
ar1[i] = Rnum.nextInt(100);
System.out.print(ar1[i] + " ");
if(ar1[i] > 70)
// increment count
count++;
// add the number greater than 70 to the average
average += ar[i];
System.out.print(ar1[i] + " ");
}
//once out of the loop devide the sum of all //integers greater than 70 (stored in average) by //the number of integers that were greater than 70 (stored in count)
average = average / count;
System.out.println(average);
}

Identifying, if there's duplicated inputted integer in Java

How am I going to identify the duplicated inputted integer like If I input 1 1 2 3 4, it will say number 1 is been duplicated
import java.util.*;
public class Haha {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] items = new int[5];
int sum;
System.out.println("Enter five integers: ");
sum = 0;
for (int counter = 0; counter < items.length; counter++) {
items[counter] = console.nextInt();
sum = sum + items[counter];
}
System.out.println("The sum of the numbers = " + sum);
System.out.print("The numbers in the reverse" + "order are: ");
for (int counter = items.length - 1; counter >= 0; counter--) {
System.out.print(items[counter] + " ");
}
System.out.println();
}
}
All you need is a Set :)
int[] arr = { 1, 1, 2, 3, 4,3 };
Set<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
boolean b = hs.add(arr[i]); // add returns false if the value is already present in the set
if (!b) {
System.out.println("duplicate value is : " + arr[i]);
}
}
O/P :
duplicate value is : 1
duplicate value is : 3

Categories

Resources