This section of code below for some reason is not taking each array item made and adding them together.
I stepped through the debugger and the array items are being created and incremented but the total += scoreArray[i];does not seem to be adding up the numbers that have been input. Instead, I am just getting just the 1st input divided by the array length as the final output
public double getAverage()
{
double total = 0.0;
for (int i = 0; i < scoreArray.length; i++)
total += scoreArray[i];
return (total / scoreArray.length);
}
Full Code
package driver;
import java.util.Scanner;
public class TestScores
{
private double[] scoreArray;
public TestScores(double[] test) throws IllegalArgumentException
{
scoreArray = new double[test.length];
for (int i = 0; i < test.length; i++)
{
if (test[i] < 0 || test[i] > 100)
throw new IllegalArgumentException("Test scores must have a value less than 100 and greater than 0.");
else
scoreArray[i] = test[i];
}
}
public double getAverage()
{
double total = 0.0;
for (int i = 0; i < scoreArray.length; i++)
total += scoreArray[i];
return (total / scoreArray.length);
}
public static void main(String[] args)
{
int score = 0;
int scores = 0;
Scanner userInput = new Scanner(System.in);
System.out.print("Enter number of test scores: ");
score = userInput.nextInt();
double[] scoreArray = new double[score];
for (int i = 0; i <= score - 1; i++)
{
System.out.print("Enter test score " + (i + 1)+ ": ");
scoreArray[scores] = userInput.nextDouble();
}
TestScores testScore = new TestScores(scoreArray);
System.out.println(testScore.getAverage());
}
}
Please change your loop of accepting user score with following:
for (int i = 0; i <= score - 1; i++)
{
System.out.print("Enter test score " + (i + 1)+ ": ");
// scoreArray[scores] = userInput.nextDouble(); <-- value of scores is zero
scoreArray[i] = userInput.nextDouble();
}
You should use "i" instead of "scores" while populating scoreArray. Currently you are populating your "scoreArray" with only last entered user input.
Related
Currently working on a project that requests the number of classes a student has left, the amount of classes taken per term, and returns the number of terms left to graduate. I'm having some trouble figuring out how to cast an integer array to a double array to figure out the amount of terms needed. Also the result needs to round up as well. I'm very new to this so any suggestions are much appreciated and critiques on how to clean up my code, thanks in advance.
import java.util.Scanner;
public class main {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows: ");
int rows = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
int [][] studentArray = new int [rows][columns];
for (int i = 0; i <= rows-1; i++) {
for (int j = 0; j <= columns-1; j++) {
if (j==0) {
System.out.print("Please enter the number of classes left for student " +(i+1)+ " : ");
studentArray[i][j] = input.nextInt();
}
else if (j>0) {
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
while (studentArray[i][j] >= 6) {
System.out.println("The number of classes per term for student " +(i+1)+ " is not valid!");
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
}
}
}
}
divide(studentArray);
}
public static void divide(int termsLeft[][]) {
for (int k = 0; k < termsLeft.length; k++) {
double result = termsLeft[k][0] / termsLeft[k][1];
if (k>=0) {
System.out.println("Student " +(k+1)+ " has " + result + " terms left to graduate.");
}
}
}
}
First of all their are some problems in your code which make it very ineffecient.
1)
for (int i = 0; i <= rows-1; i++) {
for (int j = 0; j <= columns-1; j++) {
}
In your inner and outer loop you don't have to use <= sign and subtract 1 from right value. you can use i < rows & j < columns.
2)
if (k>=0) {
System.out.println(...)
}
Their is no need to use the if statement as it is always true.
Now coming to your question.
Your can use the Math.round method to round double values into long (can store larger values than int).
double result = termsLeft[k][0]/termsLeft[k][1];
long round_result = Math.round(result);
So your final code is below :
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows: ");
int rows = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
int [][] studentArray = new int [rows][columns];
for (int i = 0; i <= rows-1; i++) {
for (int j = 0; j <= columns-1; j++) {
if (j==0) {
System.out.print("Please enter the number of classes left for student " +(i+1)+ " : ");
studentArray[i][j] = input.nextInt();
}
else if (j>0) {
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
while (studentArray[i][j] >= 6) {
System.out.println("The number of classes per term for student " +(i+1)+ " is not valid!");
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
}
}
}
}
divide(studentArray);
}
public static void divide(int[][] termsLeft) {
for (int k = 0; k < termsLeft.length; k++) {
double result = termsLeft[k][0]/termsLeft[k][1];
long round_result = Math.round(result);
System.out.println("Student " +(k+1)+ " has " + round_result + " terms left to graduate.");
}
}
}
I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}
I found an exercise in my textbook that makes this 2D array.
I have the input loop working, and the table prints successfully but I can't find a way to take the values in each row and column and print out the totals as shown in the exercise.
I have asked my professor and he said he couldn't remember how to do it with a string array. I hope there is a way to convert each number from string to an int. I assume that creating a double array would have been much easier than a String array but at this point I wouldn't know convert all my work over.
package Assignment2;
import java.util.*;
/**
*
* #author Lyan
*/
public class Exercise7_20
{
public static void sales2DArray(int salesPerson, int product, double value)
{
}
public static void main(String[] args)
{
int salesP = 0; //salesPerson set to 0
String[][] table = new String[5][5]; // A matrix of '5 rows and '5 Columns'
//For loop that replaces null values in table with 0.00
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] == null) {
table[i][j] = " 0.0";
}
}
}
//Input for salesPerson
Scanner inSales = new Scanner(System.in);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//While loop to ask for salesPerson, product, and sales amount (val)
while(salesP > 0 && salesP < 5)
{
//input for Product number
Scanner inProduct = new Scanner(System.in);
System.out.println("Enter product number");
int productNum = inProduct.nextInt();
//input for sales amount
Scanner inValue = new Scanner(System.in);
System.out.println("Enter Sales amount");
double val = inValue.nextDouble();
//sets the values onto the table.
table[productNum - 1][salesP] = " " + Double.toString(val);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//makes the 1-5 on the left hand side of the table
}
for(int i = 1; i < 6; i++)
{
table[i-1][0] = " " + i + "";
}
//Hardcoded header
System.out.println("Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total");
//Makes the 2D array to print in a box format rather than a straight line.
System.out.println(Arrays.deepToString(table).replace("],","]\n"));
//Anything below is my testing to get the total to print out for each individual salesPerson (column)
//and the totals for the products for all salesPerson (rows)
System.out.print("Total ");
String total = "";
int sum = 0;
for(int down = 0; down < 5; down++)
{
//append
}
//successfully reads the last value of each column but does not print the total
//only successfully prints the last value
for(int c = 1; c < 5; c++)
{
for(int r = 0; r < 5; r++)
{
String temp = table[r][c];
total = temp;
}
System.out.print(total + " ");
}
}
}
You can use this simple logic to find the sum of each individual row and column of your 2D array.
double[] sumOfRows = new double[5];
double[] sumOfCols = new double[5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
sumOfRows[i] = sumOfRows[i] + Double.parseDouble(table[i][j]);
sumOfCols[i] = sumOfCols[i] + Double.parseDouble(table[j][i]);
}
}
Here we declare 2 additional arrays to store the sum of each row and column respectively. You can print them according to your logic as desired.
Also note use Double.parseDouble(...) to convert a String to a double.
The purpose of my code is to display the student number and their respective grade as follows:
Student Grade
1 53
2 45
So on...
I used a 5x2 array, in which the user can input the values for the grade...
However I run in to a problem, when inputting the grades, for some reason I have to input 3 values, out of all the 3 inputted values only the 3rd is considered.
My problems:
(1) Why is it that I am even able to enter 3 values per student (Should only be able to input 1 value per student).
(2) Why is it the 3rd value that is being considered?
Here is my code:
import java.util.*;
public class practice {
public static void main(String[] args) {
int[][] studentGrade = new int[5][2];
for(int i = 0; i<5; i++) {
studentGrade[i][0] = i+1;
}
for(int j = 0; j<5; j++) {
System.out.printf("Student %s: ", j+1);
Scanner input = new Scanner(System.in);
if(input.nextInt()>=0 && input.nextInt()<=100) {
studentGrade[j][1] = input.nextInt();
}
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j);
}
}
System.out.print("\nStudent \t Grade");
for(int s=0; s<5; s++) {
System.out.print("\n" + studentGrade[s][0] +"\t" + "\t " + studentGrade[s][1]);
}
}
}
input.nextInt() consumes the next integer in the stream.
You need to do this:
Scanner input = new Scanner (System.in);
for (int j = 0; j < 5; j++) {
System.out.printf("Student %s: ", j+1);
int num = input.nextInt();
if (num >= 0 && num <= 100)
studentGrade[j][1] = num;
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j+1);
}
}
This will make it so that you read the number being input only once, and then you use that number when checking boundaries and then setting the grade.
I am trying to create an array with 'total' amount of numbers between min and max. And then, sort them using bubble sort. When i execute, i get all zeros. Could someone find what is going wrong? A prompt reply would be appreciated.
import java.util.*;
import java.util.Random;
public class final_project
{
public static void main(String[] args)
{
int numbers[];
int i, min, max, total;
int num;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a minimum random value");
min = scan.nextInt();
System.out.println("Please enter a maximum random value");
max = scan.nextInt();
System.out.println("Please enter the amount of random numbers");
total = scan.nextInt();
numbers = new int[total];
i = 0;
total = 0;
while ( i < total )
{
num = min + (int)(Math.random()*max);;
numbers[i] = num;
total += num;
i += 1; /* i = i + 1; */
}
bubbleSort(numbers, numbers.length);
System.out.println("Your Sorted Array Is: ");
for(i=0; i<numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
}
private static void bubbleSort(int[] numbers, int length)
{
int temp, counter, index;
for(counter=0; counter<length-1; counter++)
{
for(index=0; index<length-1-counter; index++)
{
if(numbers[index] > numbers[index+1])
{
temp = numbers[index];
numbers[index] = numbers[index+1];
numbers[index+1] = temp;
}
}
}
}
}
Change
while ( i < total )
to
while ( i < numbers.length )
Your loop doesn't execute:
i = 0;
total = 0;
while ( i < total )
...
Also you don't want to increment total. Replace your loop with:
for(int i = 0; i < numbers.length; ++i)
{
numbers[i] = num;
}
You should consider using a for loop instead of a while loop. A for loop is perfect for iterating through an array.