User Input to determine the length of an array in Java - java

I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.

For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.

Related

Using a scanner input to define the number of scanner inputs required

I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.

Average of an array and associate with name

Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result

How to get the sum of an Integer arraylist?

Basically Im trying to make a program that allows a teacher to input grades for a test for each student then after they've inputted the grades it gives the teacher a sum of all the grades they inputted
public static void grades(){
List<Integer> grade = new ArrayList<Integer>();
int gradetotal = IntStream.of(grades).sum;/* sum */
int gradelistnumber = 1;
int inputedgrade = 0;
while(inputedgrade != -1){
System.out.println("Enter Grade for student " + gradelistnumber + " (1-50): ");
inputedgrade = sc.nextInt();
grade.add(inputedgrade);
gradelistnumber++;
}
System.out.println("Class Average: " + gradetotal / 50 * 100);
}
I'm trying to figure out how to get the sum of the array list grades .
Here's how you sum a Collection using java 8:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String args[]) throws Exception {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(5);
System.out.println(numbers.stream().mapToInt(value -> value).sum());
}
}
In your code, you would do this to the grade list. You can set this to gradetotal after your loop.
value -> value is saying "take each argument and return it". stream() returns a Stream which doesn't have sum(). mapToInt returns an IntStream which does have sum(). That value -> value tells the code how to convert each element in the Stream into an Integer. Because each element is already an Integer, we merely have to return each element.
Instead of maintaining an array, why not just keep two temporary variables - a count and a summation?
int gradetotal = 0;
int gradelistnumber = 0;
int inputedgrade = 0;
while(inputedgrade != -1){
System.out.println("Enter Grade for student " + gradelistnumber + " (1-50): ");
inputedgrade = sc.nextInt();
gradetotal = gradetotal + inputedgrade;
gradelistnumber++;
}

How do I sort a java text file so that I can obtain the median?

I have the code below so far. I know the median is wrong because I've placed numbers in it and what I really want is for the program to extract these from the file on its own since the numbers may change. I am not sure how to have the program get the 2 numbers in order to retrieve and calculate the median. Please help. I am very new to this and it has taken me all day to get this far!
package trials;
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class trials2 {
public static void main(String[] args) throws IOException {
// This is a Scanner object that reads from the keyboard
Scanner in = new Scanner(System.in);
// The following is set to find the file
System.out.println("Please enter the name of your data file: ");
String fileName = in.next();
// The file is then to be scanned
Scanner fileToRead = new Scanner(new File(fileName));
// This loop finds the contents within the file
double sum = 0;
int numStudents = 0;
double maxVal = 0, minVal = 0;
boolean bFirstTime = true;
double currVal;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
numStudents++;
currVal = fileToRead.nextDouble();
// The following will find the maximum and minimum values within the file
if (bFirstTime) {
maxVal = currVal;
minVal = currVal;
bFirstTime = false;
} else {
maxVal = Math.max(maxVal,currVal);
minVal = Math.min(minVal, currVal);
}
sum += currVal;
} else {
fileToRead.next();
}
}
// Prints out comments and results
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println();
System.out.println("Minimum = " + minVal);
System.out.println("Maximum = " + maxVal);
System.out.println("Average score: " + sum/numStudents);
System.out.println();
System.out.println("Number of scores by letter grade: ");
System.out.println();
System.out.println("There are " + numStudents + " scores");
}
}
There are a few steps to doing this.
At the beginning of your program, create an ArrayList<Double> for storing your values in.
Within your main loop, use the list's add method to add each value as you read it.
At the end of your loop, Use Collections.sort to sort your list.
Use the following logic to work out the median.
If the size of the list is zero, then there's no median.
If the size of the list is odd, then the median is the value at position size() / 2 of the list.
If the size of the list is even, then the median is the average of the value at position size() / 2 - 1 and size() / 2 of the list.
I deliberately haven't given you code, because I think you're enjoying learning how to do this for yourself. But feel free to post a comment if you need more detail on any particular step.

Store ints into array from a file and find mean JAVA

In this program, you will find a menu with options to perform different functions on an array. This array is taken from a file called "data.txt". The file contains integers, one per line. I would like to create a method to store those integers into an array so I can call that method for when my calculations need to be done. Obviously, I have not included the entire code (it was too long). However, I was hoping that someone could help me with the first problem of computing the average. Right now, the console prints 0 for the average because besides 1, 2, 3 being in the file, the rest of the array is filled with 0's. The average I want would be 2. Any suggestions are welcome. Part of my program is below. Thanks.
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
System.out.println("You've chosen to compute the average.");
infoMenu1(sc);
break;
case 2:
infoMenu2(sc, sc);
break;
case 3:
infoMenu3(sc);
break;
case 4:
infoMenu4(sc);
break;
case 5:
infoMenu5(sc);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu1(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
int[] numbers = new int[100];
int i = 0;
while (sc.hasNextInt()) {
numbers[i] = sc.nextInt();
++i;
}
System.out.println("The average of the numbers in the file is: " + avg(numbers));
}
public static int avg(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = (sum + numbers[i]);
}
return (sum / numbers.length);
}
Just modify your method as follows:
public static int avg(int[] numbers, int len) where len is the actual numbers stored.
In your case you call:
System.out.println("The average of the numbers in the file is: " + avg(numbers, i));
And in your code for average:
for (int i = 0; i < len; i++) {
sum = (sum + numbers[i]);
}
I.e. replace numbers.length with len passed in
And do return (sum / len);
Instead of using a statically-sized array you could use a dynamically-sized List:
import java.util.List;
import java.util.LinkedList;
// . . .
private static void infoMenu1(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
List<Integer> numbers = new LinkedList<Integer>();
while (sc.hasNextInt()) {
numbers.add(sc.nextInt());
}
System.out.println("The average of the numbers in the file is: " + avg(numbers));
}
public static int avg(List<Integer> numbers) {
int sum = 0;
for (Integer i : numbers) {
sum += i;
}
return (sum / numbers.size());
}
This has added the benefit of allowing you to read in more than 100 numbers. Since the LinkedList allows you to perform an arbitrary number of add operations, each in constant time, you don't need to know how many numbers (or even an upper-bound on the count) before reading the input.
As kkonrad also mentioned, you may or may not actually want to use a floating-point value for your average. Right now you're doing integer arithmetic, which would say that the average of 1 and 2 is 1. If you want 1.5 instead, you should consider using a double to compute the average:
public static double avg(List<Integer> numbers) {
double sum = 0;
for (Integer i : numbers) {
sum += i;
}
return (sum / numbers.size());
}
I think sum should be a double and double should be the return type of your avg function
Please change your average function in such a way
private static void infoMenu1(Scanner sc) throws FileNotFoundException {
.
.
.
System.out.println("The average of the numbers in the file is: " + avg(numbers,i));
}
public static int avg(int[] numbers,int length) {
int sum = 0;
for (int i = 0; i < length; i++) {
sum = (sum + numbers[i]);
}
return (sum / length);
}
While calling average function pass i (which you counted in infoMenu1 for number of entries in data.txt) as well and use that in loop and dividing the sum. with this your loop will not run for 100 iterations and code of lines also reduced.

Categories

Resources