Java ArrayList: Utilising ArrayList for print message - java

In my Java program I have an ArrayList. What I want to do is print a number at the bottom that will say 'x amount of people have passed'
System.out.println = ("The amount of people that have more than 40 marks is " + x);
Is it possible to calculate how many numbers of marks will be more than 40 if there are an undetermined amount of marks put in, utilising an ArrayList?
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
// Create a new scanner to use in java
int[] range = { 0,29,39,69,100 };
// A new array is created with the grade boundaries
int[] inRange = new int[boundary.length - 1];
// Indexed from 0 to n-1
int markIn;
// New integer markIn
do {
// This do-while loop calculates the expression after the statements below are exectued at least once
System.out.println("Enter Mark(s):");
// Wait for user input
markIn = input.nextInt();
// markInp value is set as the value entered by user
marks.add(markIn);
for (int a=1 ; a<boundary.length ; a++)
// for loop will take the variable 'a' and compare it with varibale 'boundary', when the condition is satisfied that value of 'a' increments by 1
if (range[a-1] <= markInp && markInp <= range[a]) {
// The boundaries will define the upper and lower limits of the markInp
inRange[a-1]++;
//inRange is incremented by 1
break;
//Exit if
}
} while (markIn <= 100);
// When the mark exceeds 100, the loop is stopped
System.out.println(marks);
input.close();
} // Close the Scanner input
}

You can do something like :
int result = 0;
if(marks != null)
{
Collections.sort(marks);
for(int i=0;i<marks.size();i++)
{
if(marks.get(i) > 40)
{
result = marks.size() - i;
break;
}
}
}
marks is the arraylist and result is desired output.

If the array is already sorted, like you show in your example, then you just have to do a simple search from where you start seeing a particular score, then taking the length of the array and subtracting the position of the element that came from your search.
If the array isn't sorted, sort it and then do the search.

Related

Frequency Array and Histogram in Java

I have to make the following program.
Write a program that builds a frequency array for data values in the range 1 to 20 and then prints their histogram. The data is to be read as input from the user. Add the following functions to your program:
a. The getData function takes input from the user and stores the data in an array.
b. The printData function prints the data in the array.
c. The makeFrequency function examines the data in the array, one element at a time, and adds 1 to the corresponding element in a frequency array based on the data value.
d. The makeHistogram function prints out a vertical histogram using asterisks for each occurrence of an element. For example, if there were five value 1s and eight value 2s in the data, it would print
1: *****
2: ********
I managed to make getData function but I can't make the other 3. Any help would be appreciated. Here is my code
import java.util.Scanner;
public class FrequencyArray {
static Scanner scan = new Scanner(System.in);
public void getData() {
System.out.println("Enter the size of array: ");
int nums = scan.nextInt();
int[] a = new int[nums];
for (int i = 1; i < a.length; i++) {
System.out.print("Enter the numbers: " + i + ":");
a[i] = scan.nextInt();
}
}
public void printData() {
getData();
}
public static void main(String[] args) {
FrequencyArray array = new FrequencyArray();
array.getData();
}
}
To print such an array, all you would need is another for-loop - loop from 0 to the array's length, and print both the loop counter's value, and the value stored in the array at that index.
System.out.println(index + ":" + array[index]);
For the histogram, do a similar loop, but for each value of the array, append an asterisk to the current line for however many instances of said number there are.
System.out.print(index);
//from 0 to the amount of this number, call System.out.print("*");
System.out.println();
Use TreeMap to store the number and their frequency in a sorted order once you get the data
then iterate over the TreeMap to print the number followed by the stars denoting the count of the value
public void printData() {
int [] numArray = getData();
Map<Integer,Integer> valueCountMap = new TreeMap();
for(int i=0;i<numArray.length;i++) {
int num = numArray[i];
if(valueCountMap.get(num) == null) {
valueCountMap.put(num,0);
}
int count = valueCountMap.get(num);
valueCountMap.put(num,count+1);
}
for(Map.Entry<Integer,Integer> entry:valueCountMap.entrySet()) {
int num = entry.getKey();
int value = entry.getValue();
System.out.print(num+":");
for(int i=0;i<value;i++) {
System.out.print("*");
}
System.out.print(" ");
}
}
Following assumptions i have made getData must return interger array and you need to print in one line. Following rectification i have done to your code
in getData i = 0 not i = 1

Loop until user input length is less than or equal to previous user input [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
import java.util.Scanner;
public class userInputTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for(int i = 0; i>-1; i=i+1){
String[] giveMeAString = new String[i+1];
String x = sc.next();
giveMeAString[i]=x;
if(i>=0){
if (giveMeAString[i].length() < giveMeAString[i-1].length()){
System.out.println("The string is shorter than previous string!");
break;}
}
}
}
}
I want to loop until present user input length is less than previous user input length.
I haven't solved it for a while after many attempta.
what am I doing wrong?
I want to use Array, because I also want to print the user inputs out later on.
The only problem I have now is to make the written code work.
Couple of things to note :
you are resetting your array every time, as the declaration (memory allocation) is within 'for' loop
array size of (i+1) will allocate lot of memory when you are on higher number of attempts
giveMeAString[i-1] : i = 1 - this should be your starting point of for(). Otherwise, you will get arrayIndexOutOfBound exception since you will be accessing giveMeAString[-1] when i = 0. This is non-existent array location/element-index.
If you want to compare 2 consecutive string lengths, you need to make sure that on first iteration of the loop, you at least have 2 strings populated (or check if you are on first iteration and then continue the loop to add second string without going further).
Corrected code is :
Scanner sc = new Scanner(System.in);
//arrays are alaways static memory allocation constructs. First input should always be the array size. If this is not known
//ahead of time, use List, ArrayList etc.
int a;
System.out.println("Enter Array size in number: ");
a = sc.nextInt();
String[] giveMeAString = new String[a];
String x;
//updaing the loop initialization and condition
for(int i = 1; i>0; i=i+1){
//should NOT be creating array every time. Strings are immutable and hence costly w.r.t. memory/responseTime.
//Besides, i didn't understand the logic of creating array of String of size (i+1).
//instead, consider using resizable list (ArrayList etc). Below line is resetting your previously input values in giveMeAString[]
//String[] giveMeAString = new String[i+1];
if (i == 1) {
//adding first input to array's first index. Without this, we would get NPE. One time execution.
x = sc.next();
giveMeAString[i - 1] = x;
}
//adding next input to array's next index
x = sc.next();
giveMeAString[i]= x;
if(i>=0){
if (giveMeAString[i].length() < giveMeAString[i-1].length()){
System.out.println("The string is shorter than previous string!");
break;
}
}
}
Similar to previous answer, but using an ArrayList implementation, if the array size should not be constrained.
Scanner scn = new Scanner( System.in );
List<String> strList = new ArrayList<>();
/*
* First clase to allow logic receive at least 1 input without performing the check.
* Next clause to check if current input length is greater than previous input length, continue receiving input
*/
while ( strList.size() < 2 || strList.get( strList.size() - 1 ).length()
>= strList.get(strList.size() - 2 ).length() )
{
System.out.println(" Enter new String: " );
strList.add( scn.next() );
}
System.out.println( "Previous String is shorter." );
scn.close();
System.out.println(Arrays.toString( strList.toArray() ));
Update, Using array implementation.
Scanner scn = new Scanner( System.in );
String [] strArray = new String[0];
/*
* First clause to allow logic receive at least 1 input without
* performing the check. Next clause to check if current input length is
* greater than previous input length, continue receiving input
*/
while ( strArray.length < 2
|| strArray[strArray.length - 1].length() >= strArray[strArray.length -2].length() )
{
String[] tempArr = new String[strArray.length + 1];
for(int i = 0; i < strArray.length; i++){
tempArr[i] = strArray[i];
}
strArray = tempArr;
System.out.println( " Enter new String: " );
strArray[strArray.length - 1] = scn.next();
}
System.out.println( "Previous String is shorter." );
scn.close();
System.out.println( Arrays.toString( strArray ) );

Why can't I have a user prompted varaible be the array size?

public class Sort {
public static void main(String[] args) {
int i = 1;
Scanner input = new Scanner(System.in);
// prompts the user to get how many numbers need to be sorted
System.out.print("Please enter the number of data points: ");
int data = input.nextInt();
// this creates the new array and data sets how large it is
int [] userArray = new int[data];
// this clarifies that the value is above 0 or else it will not run
if (data < 0) {
System.out.println("The number should be positive. Exiting.");
}
// once a value over 0 is in, the loop will start to get in all user data
else {
System.out.println("Enter the data:");
}
while (i <= data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
// this calls the sortArray method to sort the values entered
sortArray(userArray);
// this will print the sorted array
System.out.println(Arrays.toString(userArray));
}
}
I have set the array size equal to what the user inputs for how many variables they will be entering to be sorted. For some reason, Java only wants a set number instead of the number that is entered by the user. Is there a way to make this work?
First of all, there are a few mistakes in your code. You are checking if(data < 0) after you create your array with int[] userArray = new int[data];. You should check it before.
Furthermore, you will get ArrayIndexOutOfBoundsException because userArray[data] does not exist. Array indices start at 0, so the last index is data-1. You need to change your while-loop to while(i < data) instead of while(i <= data).
The problem is not that you have data instead of 10 as the length of the array. The problem is as I stated above: your while-loop.
Your issue is the while loop. Because arrays are 0 based and you need to only check if i < data. By setting it to <=, you are exceeding the array length and generating and ArrayIndexOutOfBoundsException
while (i < data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
You are over-indexing the array. A more standard way for inputting the data would be
for ( int i=0; i < data; i++ ) {
userArray[i] = input.nextInt();
}

Functions/Methods and Arrays

My class has just started learning how to write code in a format with functions and methods, and this is my first attempt at it - I feel like I'm just confusing myself.
The assignment is to create a pool of numbers 1 to a randomly selected number and to store the pool in an array; then print the pool; then a user selects a number from the pool, and the program finds the divisors of that number and stores them in another array that will then be printed.
I am having problems with getting the divisors, storing them in a new array and then printing the array.
import java.util.Scanner;
import java.util.Random;
public class GetDivisors {
public static void main (String[] args){
Scanner read = new Scanner(System.in);
int []pool = new int[100];
int []divisors = new int[100];
int size;
int pick;
int numDivisor;
// Program Heading
printProgramHeading();
// Input and test
size = createPool(pool);
printPool(pool, size);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
pick=read.nextInt();
// Data Processing
numDivisor = getDivisors(pool, divisors, pick);
// Output Section
printDivisors(divisors, size, pick);
} // end main
// Function and Method Specifications
// Name : printProgramHeading
// Description : This method prints the program heading to the monitor in all caps and with a dividing line
// : followed by a blank line.
// Parameters : None.
// Return : None.
public static void printProgramHeading() {
System.out.println("\tGET DIVISORS");
System.out.println(" ************************");
System.out.println();
} // end printHeading
//Name : createPool
//Description : This funtion generates an array of consecutive integers from 1 to a randomly generated
// : number no greater than 100.
//Parameters : An integer array.
//Return : An integer (the randomly generated number), representing the size of the array.
public static int createPool(int[]pool) {
Scanner read = new Scanner(System.in);
Random random = new Random();
int size=0;
size=random.nextInt(100)+1;
pool=new int[size];
return(size);
} // end createPool
//Name : printPool
//Description : This method prints the pool of numbers to the monitor no more than 10 per line.
//Parameters : The pool array, and the size of the pool in that order.
//Return : None.
public static void printPool(int[] pool, int size) {
int index;
int count=0;
for(index=1; index<size; index++){
System.out.print(pool[index]=index);
System.out.print(" ");
count++;
if(count == 10){
System.out.println();
count=0;
} // end if loop
} // end for loop
} // end printPool
//Name : getDivisors
//Description : This funtion stores all the divisors of the user's pick into the divisor array.
//Parameters : The pool array, the divisor array, and the user's pic, in that order.
//Return : The number of divisors found.
public static int getDivisors(int[] pool, int[] divisors, int pick){
int numDivisors = 0;
int index = 0;
for(index=1; index <= pick; index++){
if(pick % index == 0){
numDivisors++;
divisors[index] = index;
} // end if loop
} // end for loop
return(numDivisors);
} // end getDivisors
//Name : printDivisors
//Description : This method prints the contents of the divisors array to the monitor all on one line with
// : a leading label.
//Parameters : The divisor array, an integer representing the number of divisors. and the user's pick
// : in that order.
//Return : None.
public static void printDivisors(int[] divisors, int size, int pick){
int index = 0;
System.out.println("The divisors of " + pick + ": " + divisors[index] + " ");
} // end printDivisors
} // end class
Thank you!
This is obviously a school project. In order for you to learn I don't want to give you the answers but i'll point out your mistakes, so that you can fix your problems.
First in this method createPool:
//Name : createPool
//Description : This funtion generates an array of consecutive integers from 1 to a randomly generated
// : number no greater than 100.
//Parameters : An integer array.
//Return : An integer (the randomly generated number), representing the size of the array.
public static int createPool(int[]pool) {
Scanner read = new Scanner(System.in);
Random random = new Random();
int size=0;
size=random.nextInt(100)+1;
pool=new int[size];
return(size);
} // end createPool
Look closer at the values that are stored in the array.
Second in method printPool:
//Name : printPool
//Description : This method prints the pool of numbers to the monitor no more than 10 per line.
//Parameters : The pool array, and the size of the pool in that order.
//Return : None.
public static void printPool(int[] pool, int size) {
int index;
int count=0;
for(index=1; index<size; index++){
System.out.print(pool[index]=index);
System.out.print(" ");
count++;
if(count == 10){
System.out.println();
count=0;
} // end if loop
} // end for loop
} // end printPool
You are updating the values of the pool. This method should only print the values in the pool. You should be setting the values of the pool in createPool, and printing the values of the pool in printPool.
Next in the getDivisors method
//Name : getDivisors
//Description : This funtion stores all the divisors of the user's pick into the divisor array.
//Parameters : The pool array, the divisor array, and the user's pic, in that order.
//Return : The number of divisors found.
public static int getDivisors(int[] pool, int[] divisors, int pick){
int num = 0;
int divisor = 0;
int numDivisors = 0;
int index = 0;
for(pool[index]=1; pool[index]<=pick; pool[index]){
num = pick % pool[index];
if(num == 0){
divisor = num;
numDivisors++;
divisors= new int[divisor];
} // end if loop
} // end for loop
return(numDivisors);
} // end getDivisors
You have a lot of things wrong with this method. First, re-look at your for loop. I really think you need to learn further about how for loop should operate and when is the best time for use for loops. Your underlying understanding of for loops in flawed. Your logic is right for calculating the divisor, but you have two issues related to this logic. 1) Relook at how you put the new divisor into the divisors array. This is related to the earlier issue of how you use the for loop. Once you solve the for loop problem, this should become more clear 2) What should you store into the divisors array when num == 0 is false? You need to handle this case, right?
Now onto the printDivisors method:
//Name : printDivisors
//Description : This method prints the contents of the divisors array to the monitor all on one line with
// : a leading label.
//Parameters : The divisor array, an integer representing the number of divisors. and the user's pick
// : in that order.
//Return : None.
public static void printDivisors(int[] divisors, int size, int pick){
int index = 0;
System.out.println("The divisors of " + pick + ": " + divisors[index] + " ");
} // end printDivisors
Once again, you really need to understand when and when-not to use a for loop. This method should print out all the values in the divisors array. Currently, this method only prints out one value in the divisors array (the first value, at index 0).
Finally, in the main() function:
public static void main (String[] args){
Scanner read = new Scanner(System.in);
int []pool = new int[100];
int []divisors = new int[100];
int size;
int pick;
int divisor;
// Program Heading
printProgramHeading();
// Input and test
size = createPool(pool);
printPool(pool, size);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
pick=read.nextInt();
// Data Processing
divisor = getDivisors(pool, divisors, pick);
// Output Section
printDivisors(divisors, size, pick);
} // end main
Should int[] pool, and int[] divisors be initialized initially with an arbitrary size of 100? Random numbers like these are usually called "magic numbers". Magic numbers should either be set as a constant with a description, or taken out of the program. Next, you print the header. This seems ok. Then you create the pool, and save the pool size into size, and print the pool with the given size passed into the function. This all seems fine. Next you poll the user for a divisor input, and call the getDivisors function with the user input. Also you save the output into a variable divisor, which represent the size of the divisor array. Now, look at the parameters you pass into printDivisors, something smells fishy here...
These are all of the issues that I see with your code. This should give you plenty of information on how to improve your mistakes. If you have anymore questions please feel free to ask.
Sorry I can't comment your question. Is it ok if you use Collections instead of arrays?
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GetDivisorsRefactored {
private static Integer[] pool;
private static Scanner read;
public static void main(String[] args) {
// Program Heading
printProgramHeading();
initPool();
System.out.println("Available list: ");
printArray(pool);
read = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
int pick=read.nextInt();
Integer[] divisors = findDivisors(pick);;
printArray(divisors);
}
private static void printArray(Integer[] someArray) {
int nextRow = 0;
for (int num: someArray){
System.out.printf("%4d,", num);
if (++nextRow > 9){
System.out.println();
nextRow =0;
}
}
}
private static Integer[] findDivisors(int pick) {
List<Integer> divisors = new ArrayList<Integer>();
for (int index = 1; index < pool.length; index++){
if ((pick % pool[index]) == 0){
divisors.add(pool[index]);
}
}
return divisors.toArray(new Integer[divisors.size()]);
}
private static void initPool() {
int size = (int) (Math.random()*100) + 1;
pool = new Integer[size];
for (int index = 0; index < pool.length; index++){
pool[index] = index;
}
}
// Function and Method Specifications
// Name : printProgramHeading
// Description : This method prints the program heading to the monitor in
// all caps and with a dividing line
// : followed by a blank line.
// Parameters : None.
// Return : None.
public static void printProgramHeading() {
System.out.println("\tGET DIVISORS");
System.out.println(" ************************");
System.out.println();
} // end printHeading
}

for loop condition and if statment

I have made a for loop and I want the loop to break when the user enters a negative value and then give a message. I do not want the program to calculate the negative value.
public class test1
{
public static void main(String[] args)
{
PrintStream output = new PrintStream(System.out);
Scanner input = new Scanner(System.in);
List<Integer> yolo = new ArrayList<Integer>();
double sum = 0;
output.println("Enter your integers\n" + "(Negative=sentinel)");
// add the values to your empty Array except the negative entries
for (int entry = input.nextInt(); entry < 0 ; entry = input.nextInt())
{
yolo.add(entry);
if (entry >= 0 )
{
sum += entry;
}
else {
output.println("Your list is empty");
}
}
I tried using Outerloop:, and break outerloop; but it breaks the loop even at positive integers.
change it to
for ( int entry = input.nextInt(); entry >= 0; entry = input.nextInt())
because currently the loop is only running when the entered number is < 0.
So the loop has the semantic(meaning):
run while the entries are >= 0, read every time from the input to entry
So the loop finishes, when a user enters a negative number.
// add the values to your empty Array except the negative entries
It looks like you're also missing out a small thing.
What you want to do is:
if (entry >= 0){
yolo.add(entry);
sum += entry;
}
For your problem, I think your for-loop as declared is wrong, because each time you call input.nextInt() it will ask for a new input, and you can put negative values the second time whatever happens.

Categories