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.
Related
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]);
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.
I know that java can't normally return two values, but I'm trying to return the value as a method.. From there I want to use the values of score1 and maxScore1 in a string in the main method. getHwGrades is the method I'm having issues with. I get "error: cannot find symbol". I'm not allowed to use arrays for this program. On another note, I'm also not supposed to use any if/else statements, but I could not find any other way to limit the value of discussionGrade to 20. Any help is appreciated
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
Scanner getG = new Scanner(System.in);
int weight1;
int weight2;
int weight3;
int score2 = 0;
int maxScore2 = 0;
int sections;
int discussionGrade;
System.out.println("What is the weight for the HW and Exam 1?");
weight1 = getG.nextInt();
weight2 = getG.nextInt();
weight3 = getWeight(weight1, weight2);
System.out.println("Using weights of " + weight1 + " " + weight2 + " " + weight3);
getHwGrades();
sections = numberSections();
discussionGrade = calcDGrade(sections);
System.out.println("What is your grade for exam1?"); //move under hw total points and final grade, add curve
score2 = getG.nextInt();
maxScore2 = getG.nextInt();
System.out.println("Total Points =" + (score1+ discussionGrade) + "/ "(maxScore1 + 20));
}
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
int nOfA;
Scanner getG = new Scanner(System.in);
System.out.println("How many HW assignments are there?");
nOfA = getG.nextInt();
for (int i = 1; i <= nOfA; i++) //loop that asks for the grades corresponding to the amount of hw assignments there were
{
System.out.println("What is your grade and then the max grade for assignment " + i + "?");
score1 += getG.nextInt();
maxScore1 += getG.nextInt();
}
return new getHwGrade(score1, maxScore1); //returns results of inputs into method holding the 2 variables
}
public static int numberSections() //finds out how many sections the student attended
{
Scanner getG = new Scanner(System.in);
System.out.println("How many sections did you attend?");
return getG.nextInt();
}
public static int calcDGrade(int sections) //method to calculate the grade for the students sections
{
int maxDGrade = ((sections*4)); if (maxDGrade > 20) //limits total score to 20
{
return 20;
}
else
{
return maxDGrade;
}
}
public static int getWeight(int weight1, int weight2)//returns the weight that will be used for weight3
{
return (100-(weight1 + weight2));
}
public static double round2(double number)
{
return Math.round(number * 100.0) / 100.0;
}
}
Since you can only return a single value, you need to return a single value. :-) Normally if a method needs to return complex information, the way you have it do that is either:
Return a newly-created instance of a class that has fields for the individual pieces of information
Have the method fill in an instance of such a class that's passed to it (usually not ideal barring a good reason for doing it)
So for instance:
class HwGrades {
private int score1;
private int maxScore1;
ScoreInfo(int _score1, int _maxScore1) {
this.score1 = _score1;
this.maxScore1 = _maxScore1;
}
// ...accessors as appropriate, presumably at least getters...
}
Then return an instance of HwGrades from getHwGrades:
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
// ...
return new HwGrades(score1, maxScore1);
}
If you needed, you could further decouple things by making HwGrades an interface, which you then implement with a private class, so that the API isn't tied to a specific class. Almost certainly overkill for a small school project.
getHwGrade is expected to be a class.
Have a class like this
class getHwGrade{
int a;
int b;
public getHwGrade(int a,b){
this.a=a;this.b=b;
}
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)
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