Asking the user to enter amount of items to an array - java

I'm really new to Java and I am having some difficulty with the basics of arrays. Some help would be greatly appreciated :).
I created a program that asks the user to enter values into an array. The program then tells the user how many items are in the array, the even numbers that are in the array, the odd numbers in the array and the average of all the numbers in the array.
My problem is this: At present my program has a set number of values in the array which is 5 items. I want to change this so that the user can determine the amount of items they want in the array, and ask the user to continually add values to the array until they enter 'Q' to quit entering values so that the program can continue.
I do not want to modify my code, just the part where the user determines the amount of items in the array.
This is my code:
//main class
public class Even_number_array {
public static void main(String[] args) {
array_class obj=new array_class();
obj.get_numbers();
obj.set_arraylist();
obj.set_numbers();
obj.get_average_of_array();
}
}
//another class
import java.util.Scanner;
public class array_class {
private int[] arr=new int[5]; //here is where I would like to modify my code so
//that the user can determine amount of items in array
Scanner keyboard=new Scanner(System.in);
public int[] get_numbers() //asks user to add items to array
{
System.out.println("Please enter numbers for array :");
for (int i=0; i<this.arr.length; i++)
{
this.arr[i] = keyboard.nextInt();
}
System.out.println("There are "+((arr.length))+ " numbers in array");
return this.arr;
}
public void set_numbers() //Tells user what even & odd numbers are in array
{
System.out.println();
System.out.println("These even numbers were found in the array:");
for (int i=0; i<arr.length;i++)
{
if (arr[i]%2==0)
{
System.out.print(arr[i]+" ");
System.out.println();
}
}
System.out.println("These odd numbers were found in the array:");
for (int i=0; i<arr.length;i++)
{
if ((arr[i]%2)!=0)
{
System.out.print(arr[i]+" ");
}
}
}
public void set_arraylist() //Dispalys all items in array
{
System.out.println("These are the numbers currently in your array: ");
for (int i=0; i<arr.length; i++ )
{
System.out.print(this.arr[i]+ " ");
}
}
public double get_average_of_array() //Gets average of all items in array
{
double sum=0;
double average=0;
System.out.println();
System.out.println("the average is: ");
for (int i=0; i<this.arr.length; i++)
{
sum=sum+arr[i];
average =sum/arr.length;
}
System.out.println(average);
return average;
}
}
Any help would be great!

Try:
public int[] get_numbers() {
System.out.println("Please enter numbers for array :");
int size = keyboard.nextInt();
int[] values = new int[size]; // create a new array with the given size
for (int i = 0; i < size; i++) {
values[i] = keyboard.nextInt();
}
System.out.println("There are "+((values.length))+ " numbers in array");
this.arr = values;
return this.arr;
}

Sorry i don't really get what you are asking but maybe you mean this
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
int[] array = new int[scanner.nextInt()];
System.out.println(array.length);
Sorry i'm pretty bad in java only been learning it for 2 months now

ArrayList is the object you want. It has functions that allow you to append values at the end. It's a dynamic array in the sense that you can mutate it at will.

Using an ArrayList instead of arrays would be the easiest way to accomplish exactly what you are trying to do.
Another option is to ask how many numbers the person plans on entering from the start.
If, for some weird reason, you are only trying to use arrays without asking the user how many numbers they want to enter... a third option would be to create a new array (being one size larger than the previous array) each time the user enters another number.
Some guidance for the last piece...
public int[] get_numbers() //asks user to add items to array
{
System.out.println("Please enter numbers for array :");
//Instead of this for loop, you will want a while loop. Similar to "while (userHasntEnteredQ)"
for (int i=0; i<this.arr.length; i++)
{
//You will want to create a new array here.
// int[] newArray = new int[this.arr.length + 1];
// Then copy the values of this.arr to newArray
// Then place the keyboard.nextInt() into the last spot of newArray
// Then set this.arr to newArray
}
System.out.println("There are "+((arr.length))+ " numbers in array");
return this.arr;
}

If you want the user to determine how many items are in the array, add this in to your code:
System.out.println("Enter the amount of items in the array:");
while (keyboard.hasNextInt()) {
int i = keyboard.nextInt();
}
private int[] arr = new int[i];
However, you won't be able to add more items to the array than the user defined without getting an ArrayIndexOutOfBoundsException, so there is a better way to do this that uses something called an ArrayList. With an ArrayList, you don't have to worry about setting the size of the array before using it; it just expands automatically when new items are added unless you explicitly set a size for it. An ArrayList can be of any object, but to make it only for integers, declare it like this:
ArrayList<Integer> arr = new ArrayList<>();
To add items to the ArrayList:
arr.add(item);
To read a value by its index:
arr.get(index);
To get the index of an item:
int index = arr.indexOf(item);
There is much more that you can do with an ArrayList. Read about it here.

Related

Sorting array elements and indices, and outputting in table form

The Java program below asks the user for UP TO 25 test scores, it then stores them in an array, averages them, and prints out in table form the inputted test grades as well as the calculated average. There is an unused sorting algorithm present as its own method named selectionSort. This is actually from a textbook.
I need to use that method to sort the array and create an additional output like the second example shown below where the test scores are displayed in ascending order. The only hint I have is that I need to make another array of the indices of the first array.
I'm not supposed to put any additional code in the main method, so I assume I will need a separate method? Or can I put all of the additional code in the selectionSort method so I only have to call one method? All I understand is that the selectionSort method sorts the elements, but not the indices so it won't show Test 1, 2, 3 like it's supposed to. So I need to sort the indices as well, and then somehow print both? How do I do this? Thanks
The current output is like this.
unsorted
I need an additional output like this. "Table of sorted test scores"
sorted
public class ArrayIntro2 {
public static void main(String[] args) {
//integer array
int [] TestGrades = new int[25];
//creating object of ArrayIntro2T
ArrayIntro2T pass = new ArrayIntro2T(TestGrades, 0, 0, 0);
//getting total and filling array
int scoreCount = ArrayIntro2T.FillArray(TestGrades, 0);
//get average score
double avg = pass.ComputeAverage(TestGrades, scoreCount);
//outputting table
ArrayIntro2T.OutputArray(TestGrades,scoreCount,avg);
}
}
//new class to store methods
class ArrayIntro2T{
//variable declaration
double CalcAvg = 0;
int ScoreTotal = 0;
int ScoreCount = 0;
int [] TestGrades = new int[25];
//constructor
public ArrayIntro2T(int [] TestGradesT, int ScoreCountT, double CalcAvgT, int ScoreTotalT)
{
TestGrades = TestGradesT;
ScoreCount = ScoreCountT;
CalcAvg = CalcAvgT;
ScoreTotal = ScoreTotalT;
}
//method to fill array
public static int FillArray(int [] TestGrades, int ScoreCount)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter test scores one at a time, up to 25 values or enter -1 to quit" );
TestGrades[ScoreCount]= scan.nextInt();
if(TestGrades[ScoreCount]==-1)
{
System.out.println("You have chosen to quit ");
}
while(TestGrades[ScoreCount]>=0 && ScoreCount<=25)
{
ScoreCount++;
System.out.println("Enter the next test score or -1 to finish ");
TestGrades[ScoreCount] = scan.nextInt();
}
return ScoreCount;
}
//method to compute average
public double ComputeAverage(int [] TestGrades,int ScoreCount)
{
for(int i=0; i<ScoreCount;i++)
{
ScoreTotal += TestGrades[i];
CalcAvg = (double)ScoreTotal/(double)ScoreCount;
}
return CalcAvg;
}
public static void selectionSort(int[] TestGrades){
int startScan, index, minIndex, minValue;
for(startScan=0; startScan<(TestGrades.length-1);startScan++){
minIndex = startScan;
minValue = TestGrades[startScan];
for(index = startScan+1;index<TestGrades.length; index++){
if(TestGrades[index]<minValue)
{
minValue=TestGrades[index];
minIndex=index;
}
}
TestGrades[minIndex]=TestGrades[startScan];
TestGrades[startScan]=minValue;
}
}
//method to output scores and average
public static void OutputArray(int [] TestGrades,int ScoreCount, double CalcAvg)
{
System.out.println("Grade Number\t\tGrade Value");
for(int i=0; i<ScoreCount;i++)
{
System.out.println((i+1)+"\t"+"\t"+"\t"+TestGrades[i]);
}
System.out.printf("Calculated Average\t"+ "%.2f%%", CalcAvg);
}
}
I've tried calling the selectionSort method in the main method, and also using Array.sort although they produce the same result. When I do that, I get an output that looks like this:
failed attempt
Why are you thinking about sorting the indices? The sorted output that you expect doesn't change the order of the indices. Adding the call to selectionSort() in the main method makes sense, but if you're not supposed to do that, you can add it at the end of FillArray(), or the start of OutputArray().
As to the issue with your output, you need to look into sorting only the scores that were entered by the user, and not every entry in the array.

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();
}

Asking the user what size the array should be

import java.util.Scanner;
/**
* Created by b00598439 on 30/09/2015.
*/
public class Assessment1 {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
for (int i = 1; i<=2; i=>3; i++){
answer[i] nextInt(); //Get integer entered, if different from 1 or 2, if any other number then quit
}
System.out.println("What size of array would you like?");
int SIZE = in.nextInt(); //What size should the array be?
int [] answer = new int[SIZE]; //Lets user read into the program
System.out.println("The total of the numbers in the program is: " + answer); //Gives total of numbers
System.out.println("The average of the numbers in the program is: " + avg);
int count = 0;
for (int i = 0) ; //Calculating the average
I have been trying to get the code sorted to write to screen and follow on through for the size of the array. I have to get the user to select an option 1, or option 2, if option 1 or 2 isn't chosen then I have to terminate the program. I cannot even get the first part printing or working and this is what I have to do:
1) If the array option is chosen, the program should:
• Ask the user what the size of the array should be
• Let the user read in the numbers into the array
• Output the total of the numbers stored in the array
• Output the average of the numbers stored in the array
I have been sitting here for 4 hours and still getting nowhere
Any help would be appreciated
This can be done in many ways,I have done it in a simple way so you can understand the whole code step by step.By the way,you haven't explained what you want the program to do if option 2 was chosen.You can remove the option 2 by deleting the "case 2:".See the code.
import java.util.Scanner;
public class Assessment1 {
public static void main (String args[]) {
int average,sum=0;
Scanner input = new Scanner(System.in);
Scanner length = new Scanner(System.in);
Scanner option = new Scanner(System.in);
System.out.println("Enter 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
int x=option.nextInt();
switch(x){
case 1:
System.out.println("Input array size: ");
int len=length.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
sum += numbers[i];
}
average=sum/len;
System.out.println("Total sum of all numbers: "+sum);
System.out.println("Average of all numbers: "+average);
case 2:
//insert your "ArrayList code here,you haven't explained what you want here
default:
System.out.println("Program terminated.");
}
}
}
Ok, I developed a little more the code. I put it inside a while loop... it goes back to the beginning and asks to again to enter the options... you enter any number other than 1 or 2 and you get out. I tested it and it works ok in the console. Just a comment.. you are getting the average in integer values... if you would like to get doubles then you have to use doubles and use nextDouble instead of nextInt. Hope that it helps.
import java.util.Scanner;
public class Assessment{
public static void main(String[] args){
// Scanner to get the initial number options
Scanner in = new Scanner(System.in);
// Scanner to get numbers to sum
Scanner numSc = new Scanner(System.in);
// Declaration of variables and array
int answer = 0; //You need int answer, don't need an array by now
int numAnswer;
int sum = 0;
int average;
// Loop the program
while (true){
System.out.println("Enter number 1 for arrays, 2 for arraylists, any other to quit");
// Using in Scanner to test for integer input
if(in.hasNextInt()){
// If there is an integer then give it to numAnswer
numAnswer = in.nextInt();
// What to do if the option is 1, 2 or other number
switch(numAnswer)
{
case 1:
case 2:
answer = numAnswer;
break;
default:
System.exit(0); // Out of the program
}
}
// If answer variable got number 1
if (answer == 1){
// New Scanner to get the size of the array
Scanner sizeSc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
// Getting the size of the array with sizeSc Scanner
int size = sizeSc.nextInt();
// Making a new array with the size of size variable
int[] inputNums = new int[size];
// Looping to get input numbers
for (int i = 0; i < inputNums.length; i++){
System.out.println("Enter a number in the array: ");
//Getting the numbers from console with numSc Scanner
inputNums[i] = numSc.nextInt();
sum += inputNums[i]; //Getting the sum of each number
}
average = (sum/size);
System.out.println("Sum of numbers: " + sum);
System.out.println("Average of numbers: " + average);
System.out.println(" ");
} else {
System.out.println("YOUR CODE TO THE LISTARRAY");
}
}
}
}

Dynamic array in Java - so we can decide the size of an array according to user's input

I just wrote this basic program. It takes 5 values from the user and stores all of them in an array and tells the highest number.
import java.util.Scanner;
public class HighestNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] numbers = new int [5];
int max = numbers[0];
System.out.println("Enter " + numbers.length + " numbers:");
for (int i=0; i<numbers.length; i++) {
numbers[i] = input.nextInt();
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("The highest number is:" +max);
}
}
I'd like to take off the restriction of 5 numbers and allow the user to add as many numbers as he wants. How can I do that?
Appreciate the assistance. :)
Thanks
If the user knows the number of numbers in advance (before they enter the actual numbers):
Ask the user how many numbers they want to enter:
System.out.println("How many numbers?");
int numberOfNumbers = input.nextInt();
Use that as the array size:
int[] numbers = new int[numberOfNumbers];
If the user shouldn't need to know the number of numbers in advance (e.g. if they should be able to type "stop" after the last number) then you should consider using a List instead.
Alternatively, you could use an ArrayList and keep on adding elements until the user enters a blank line. Here is a tutorial on using ArrayList.
Some pseudocode could be:
numbers = new list
while true
line = readLine
if line == ""
then
break
else
numbers.add(convertToInteger(line))
...
The benefit of this approach is that the user does not need to even count how many numbers he/she wants to enter.

Input and storing Strings in two-dimensional arrays

My teacher explained two dimensional arrays in literally two paragraphs. He didn't give me any information on how to create them besides that and now I have to do an assignment.
I've read up a lot about it and I somewhat understand how a 2D array is like an array of arrays, but I'm still completely and utterly confused about how to apply it.
The assignment itself is very simple. It asks me to create a program that will ask a user for ten Criminal Records, (name, crime, year). This program will store the records in a two-dimensional array and then sort them using the selection sort.
I know this is probably wrong, but here is what I have so far based on what I've read:
public static void main(String[] args)throws IOException {
//create array
String[][] Criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 1; row < Criminals.length; row++){
for (int col = 1; col < Criminals[row].length; col++){
System.out.print("Enter a criminal name: ");
Criminals[row][col] = br.readLine();
}
}
}
So far, I'm just trying to get the input and store it.
(Please try to be patient and thorough with me! Coding isn't my strongest point, but I'm trying to learn.) Any help would be amazing! Thanks in advance. :)
It looks fine for the most part. You should index arrays starting from 0, not 1. Your current code works but I'm guessing you don't want the same prompt for all entries. Thus it may be a good idea to use a single loop instead:
for (int row = 0; row < Criminals.length; row++) {
System.out.print("Enter a criminal name: ");
Criminals[row][0] = br.readLine();
System.out.print("Enter a crime: ");
Criminals[row][1] = br.readLine();
System.out.print("Enter a year: ");
Criminals[row][2] = br.readLine();
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//create array
String[][] criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 0; row < criminals.length; row++){
System.out.print("Enter a criminal name: ");
while(in.hasNext()){
criminals[row][0] = in.nextLine();
System.out.print("Enter a crime: ");
criminals[row][1] = in.nextLine();
System.out.print("Enter a year: ");
criminals[row][2] = in.nextLine();
}
}
}
}
This will print the commands you need from user and will store it in criminals. You may sort in the end. Since you didn't gave any information how you want it sorted, I will leave it for you to do it.
PS: I changed the 2d array name from Criminals to criminals, it's a java's good practice to not use capital words for attributes and variables (use it only for class names)

Categories