Looping with different variables? - java

Before this the user inputs an int for numOfTimes. Say it's 5. This will ask the question 5 times. But each time through it will erase the previous value in hrs1. It needs to be a separate variable. So if numOfTimes=5 Then I should get 5 different doubles for "Hour " and 5 different doubles for "Minute ". (assuming the user inputs different times) but they all need to be stored in different variables. How should I do this?
Thank you my question has been answered!

use an array ..
int a[] = new int[5];
for(int i =0;i<5;i++){
a[i] = //your value
}

You just need to put your "calculate average" code outside the for loop. I am not sure exactly how you want to calculate the average. But here are two simple ways.
Method one - keep track of the totals and calculate the basic average.
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
double hrTotal = 0;
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hrTotal += hrs1;
minTotal += min1;
}
//calculate average
double avdHr1 = hrTotal/numOfTimes;
double timeMin1 = minTotal/numOfTimes;
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}
}
Method 2 - Use lists and iterate twice
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
ArrayList<Double> hours = new ArrayList<>();
ArrayList<Double> minutes = new ArrayList<>();
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hours.add(hrs1);
minutes.add(min1);
}
//calculate average
double avgHr1 = 0;
double timeMin1 = 0:
for (int i = 0; i < hours.size(); i++) {
double hour = hours.get(i);
double minute = minutes.get(i);
//ToDo: calculate average so far
}
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}

You can use arrays to store the information the user has input. Before the loop, make an array using the new keyword, e.g. double[] hrs=new double[numOfTimes]. In the loop, write to different locations in the array for each input, hrs[i]=in.nextDouble(). You can later read from a position on the array using the syntax 'name[index]', such as 'hrs[2]'. Note that for java and many other languages, arrays start at 0. This means for an array [1,2,3] named arr, arr[1] equals 2 instead of 1. This means it would be best if your for loop was changed from for(int i=1;i<=numofTimes;i++) to 'for(int i=0;i

<SOAPBOX,RANT,HIGHHORSE>
This is more of a code review than a straight answer, but something has been bugging me about newbie questions that I've observed on stackoverrflow.
When developing, I avoid keyboard input like the plague. It is such drudgery, especially with a loop such as in this program. So many newbie questions have user-keyboard input. Why?! It makes development so much more difficult!
I've rewritten your program to add the ability for testing data, completely avoiding the need for user-input during development. When testing is over, just switch the test/live comments around.
I'm sure there's a more elegant way, but this style has worked well for me, and I recommend it.
</SOAPBOX,RANT,HIGHHORSE>
import java.util.*;
import static java.lang.Math.abs;
public class AverageTimeWTestingData {
public static void main(String[] args) {
HourMin24[] ahm = null;
//EXACTLY ONE of the following lines must be commented out
//Test only:
ahm = getTestData();
//Live only:
// ahm = getDataFromUserInput();
double dTotalHours = 0.0;
for (HourMin24 hm : ahm){
System.out.println("Time: " + hm.iHour + ":" + hm.iMin);
dTotalHours += hm.iHour + (hm.iMin / 60);
}
System.out.println("Average time (" + ahm.length + "): " + (dTotalHours / ahm.length));
}
private static final HourMin24[] getDataFromUserInput() {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
ArrayList<HourMin24> al24 = new ArrayList<HourMin24>(numOfTimes);
while(numOfTimes < 0) {
System.out.println("What Time (military time): ");
System.out.print("Hour ");
int iHour = in.nextInt();
System.out.print("Minute ");
int iMin = in.nextInt();
al24.add(new HourMin24(iHour, iMin));
numOfTimes--;
}
return al24.toArray(new HourMin24[al24.size()]);
}
private static final HourMin24[] getTestData() {
System.out.println("TEST MODE ON");
return new HourMin24[] {
new HourMin24(13, 1),
new HourMin24(23, 19),
new HourMin24(0, 59),
new HourMin24(16, 16),
};
}
}
class HourMin24 {
public int iHour;
public int iMin;
public HourMin24(int i_hour, int i_min) {
iHour = i_hour;
iMin = i_min;
}
}
Output:
[C:\java_code\]java AverageTimeWTestingData
TEST MODE ON
Time: 13:1
Time: 23:19
Time: 0:59
Time: 16:16
Average time (4): 13.0

Related

Take Average of an Array using Recursion

I'm trying to create a program that will take a user input, input that data into an dynamic array, and then recursively finds the average. The first part of my code works. This allows the newly created array to be passed to the method.
public static void main(String args[])
{
int i = 0;
int sum = 0;
double runningTotal = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
}
findAverage();
for (i=0; i < newClassSize.length; i++){
sum = sum + newClassSize[i];
}
System.out.println(Arrays.toString(newClassSize));
keyboard.close();
}
}
This is where I'm getting confused and confusing myself however. How would I pass the newly created array to the findAverage() method? I would then need to also have that be saved to an accumulator and then devided. Is there a better way to do this? This is my current findAverage() method but I'm confusing myself on my implementation.
public double findAverage(int classAverage, int baseCase, double runningAverage)
{
runningAverage = 0;
int sum = 0;
if (newClassSize.length - 1 > baseCase)
runningAverage = newClassSize.length;
return findAverage();
System.out.println("The class average is " + classAverage);
}
Hopefully I understood your question correctly but heres how to do it below.
The basic idea is that when the index reaches the length of the array in the
recursive function that's the base case. So all you have to do is add to the sum at each index point in the array, and just keep passing in the updated index and sum into the recursive function.
class Main {
public static void main(String[] args) {
int newClassSize[] = {1,2,3}; // User Input let say
double average = findAverage(newClassSize);
System.out.println(average);
}
public static double findAverage(int[] arr){
// Avoid division by zero error
if (arr.length==0){
return 0;
}
return findAverageHelper(arr,0,0);
}
public static double findAverageHelper(int[] arr, int index,int sum){
if (index==arr.length){ // Base Case
return (double) sum/arr.length;
}
// Increase index and add current value at index to sum
return findAverageHelper(arr,index+1,sum+=arr[index]);
}
}

How can I get the system output value after the whole loop is done?

this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);

Output will not print the correct information

I'm trying to make a program which asks the user a particular bird then how many of them they had seen at that point. If the use at any point enters the word 'END' then the system should print out the most seen bird and the number seen. However, when running my program if I enter 'END' at random points it instead returns that the most seen was END with 0 seen. I can't figure out how to make it work. I've tried different methods but it's just not working properly. Also, I've set the maximum array limit to 10 possitions but it continues after 10 and if i enter a value the system crashes. Have I written the limit part properly? Or am I missing something important?
import java.util.Scanner;
public class testing
{
public static void main (String[] param)
{
birdInput();
most();
System.exit(0);
}
public static void birdInput()
{
int i = 0;
String birdInput;
int numberInput;
Scanner scanner = new Scanner(System.in);
int maxVal = Integer.MIN_VALUE;
int maxValIndex = -1;
while (true)
{
System.out.println("What bird did you see?");
birdInput = scanner.nextLine();
if (birdInput.equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.exit(0);
}
else
{
String[] birds = new String[10];
int[] numbers = new int[10];
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
if (birds[i].equals("END"))
{
maxVal = numbers[i];
maxValIndex = i;
System.out.print("\nThe most common bird that you saw was the " + birds[maxValIndex] + " with " + maxVal + " being seen in total\n");
System.exit(0);
}
}
}
}
public static void most()
{
System.out.println("fdff");
}
}
This is my edit of Till Hemmerich's answer to my issue. I tried to remove the global variables and so combine the entire code into 1 method. However, I'm still having some issues. Been working at it but really confused.
import java.util.Scanner;
public class birds2
{
public static void main(String[] param)
{
birdInput();
System.exit(0);
}
public static void birdInput()
{
Scanner scanner = new Scanner(System.in);
String[] birds = new String[99999999];
int[] numbers = new int[99999999];
int i = 0;
int maxIndex;
while (i <= birds.length)
{
System.out.println("What bird did you see?");
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
}
int newnumber = numbers[i];
if ((newnumber > numbers.length))
{
maxIndex = i;
i++;
}
if (birds[i].toUpperCase().equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
}
}
You're re-declaring the birds and numbers arrays in each iteration of the loop. They should be declared and initialized only once, before the loop.
I changed a lot so im going to explain my changes here in total.
First of all i had to move the Array Definition out of your while-loop as >mentioned above, since other wise you would override these Arrays every time.
I also made them globally accessible to work with them in other methods.
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
in general I re structured the whole code a little bit to make it more readable and a little bit more object-orientated.
For example I created an method called inputCheck() which returns our input as a String and check if it equals END so you do not have to write your logic for this twice. (it also considers writing end lower or Uppercased by just Upper our input before checking it"if (input.toUpperCase().equals("END"))")
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
this method can now be called every time you need an input like this:
birds[i] = inputCheck();
but you need to be carefull if you want to get an integer out of it you first have to parse it like this:Integer.parseInt(inputCheck())
after that I wrote a method to search for the biggest Value in your numbers Array and getting its index:
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
it takes an int array as parameter and returns the index of the highest element in there as an Integer. Called like this:maxIndex = getMaxIndex(numbers);
Then after that I rewrote your end method. It now just calles our getMaxIndex method and prints some output to the console.
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
to fix your last problem (crashing after more then 10 inputs)I changed your while-loop. Since your array only has 10 places to put things it crashes if you try to put information in place number 11. it not looks like this:while (i <= birds.length) instead of while (true) this way the max loops it can take is the amout of places Array birds has and it wont crash anymore.
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
Here is the whole code in total:
import java.util.Scanner;
/**
*
* #author E0268617
*/
public class JavaApplication1 {
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
public static void main(String[] param) {
birdInput();
most();
System.exit(0);
}
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
public static void most() {
System.out.println("fdff");
}
}
I hope you understand where the Problems had been hidden if you have any Questions hit me up.

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.

How do you incorperate an AVERAGE and LETTERGRADE in a java program which has 2D Array

I have written a program with minimal errors but do not know where I should place the Average or Letter grade function:
package org.education.tutorial;
import java.util.Scanner;
public class GradingScale
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the number of students attending your current session :");
int numberOfStudents = keyboard.nextInt();
System.out.println();
System.out.print("Also, please enter the amount of exams taken during the duration of the course : ");
int examScores = keyboard.nextInt();
AssignValueToArray(numberOfStudents, examScores);
keyboard.close();
}
public static void AssignValueToArray(int amountOfStudents, int amountOfExams)
{
int[][] overallScore = new int[amountOfStudents][amountOfExams];
Scanner keyboardArray = new Scanner(System.in);
int numberValue = 1;
for (int index = 0; index < amountOfStudents; index++)
{
System.out.println ("\n" + "Please submit Student #" + numberValue + " 's score :" );
for(int indexOfHomeWork=0; indexOfHomeWork < amountOfExams; indexOfHomeWork++)
{
overallScore[index][indexOfHomeWork] = keyboardArray.nextInt();
}
numberValue++;
}
DisplayvalueInArray(overallScore);
keyboardArray.close();
}
public static void DisplayvalueInArray(int[][] overallScoreArray)
{
System.out.println ("The students' scores are posted below : " + "\n");
int studentCount = 1;
for (int index = 0; index < overallScoreArray.length; index++)
{
System.out.print("Grades for student " + studentCount +": ");
for (int indexOfHomeWork = 0; indexOfHomeWork < overallScoreArray[index].length;
indexOfHomeWork++)
{
System.out.print(overallScoreArray[index][indexOfHomeWork]+"\t");
}
System.out.println();
studentCount++;
}
}
I would highly recommend learning how to use variable scope and possibly objects before doing something such as this.
You never declare any variables in the class's scope.
Most of your functions don't affect anything outside their own scope, and therefore shouldn't be functions. Instead use comments to encapsulate.
Many of your variables are named poorly, instead of keyboardArray, which is not an array at all, do something like kb, or keyboardScanner
For computing average and lettergrades, think 'what am i averaging' and use that as your parameter, with the average as your return type, so something like static int average(int[] scores)

Categories

Resources