I'm relatively new to the world of OOP, and for some reason, the console of IntelliJ and Eclipse doesn't give me an output in the console for the following program. I'm trying to store 12 numbers into an array using scanner and to find the standard deviation, mean, lowest number, and highest number. Can anyone spot what's wrong?
import java.util.Arrays;
import java.util.Scanner;
public class untitled
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int[] grades = new int[12];
int size = grades.length;
for (int i = 0; i < size; i++)
{
grades[i] = in.nextInt();
}
Arrays.sort(grades);
int low = grades[0];
int high = grades[11];
int sum = 0;
for (int i: grades)
{
sum += i;
}
int m = sum / size;
double var = 0;
double variance;
double sd;
for (int i = 0; i < size; i++)
{
var = var + ((grades[i] - m) * (grades[i] - m));
}
variance = (int) var / size;
sd = Math.pow(variance,.5);
String lowest = ("Lowest Grade:" + low);
String highest = ("Highest Grade:" + high);
String average = ("Average Grade:" + m);
String standdev = ("Standard Dev.:" + sd);
System.out.println(lowest);
System.out.println(highest);
System.out.println(average);
System.out.println(standdev);
}
}
Thanks.
What you have done is to accept 12 inputs.. try entering 12 inputs in console and then your output will appear..
And yeah this doesnt seem to use OOP concepts. Please refer this link for more info regarding OOPS :
http://en.wikipedia.org/wiki/Object-oriented_programming
The problem is, that you need to enter values first, before the calculation and output can continue. Without having some printed text on the console (like "Enter a new number: ") the console will just stay empty.
You could either enter 12 numbers, or fill the list automatically with Random values. In this case the output will immediately be visible on the console.
...
nt[] grades = new int[12];
int size = grades.length;
Random random = new Random();
for (int i = 0; i < size; i++) {
grades[i] = random.nextInt(15); // value between 0 and 14
}
Arrays.sort(grades);
int low = grades[0];
...
Related
The final output will show who has the highest grade and who has the lowest grade.
I'm lost on how to call the lowest name/grade to the final output.
In the code I have some comments on where I'm stuck with the "currentMinIndex", the "currentMaxIndex" works just fine and will show it to the final output. I tried to mirror it but it isn't going how I expected. Not sure if something with "(int k = 1; k>= m; k++)" is incorrect.
import java.util.*;
public class MyArrayEX {
// Sort grades lowest on top
public static int[] reverseInt(int[] array) {
int[] input = new int[array.length];
for (int i = 0, j = input.length - 1; i < array.length; i++, j--) {
input[j] = array[i];
}
return input;
}
public static void main(String[] args) {
// Scanners
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// Input amount
System.out.print("\nEnter number of students: ");
int numOfStu = input.nextInt(); // Number of Students
int[] grades = new int[numOfStu];
String[] names = new String[numOfStu];
// Start loop, amount is based off of "numOfStu"
for (int i = 0; i < numOfStu; i++) {
System.out.print("\rEnter student first name: ");
String name = keyboard.next();
System.out.print("Enter the students grade: ");
int grade = input.nextInt();
// Assigning i
names[i] = name;
grades[i] = grade;
//System.out.println("");
}
// This is the area that sorts it from least to greatest
// i is the indexed value of the last number in array
for (int i = grades.length - 1; i > 0; i--) {
// Resets both to 0 to start at the beginning of the array
int currentMax = grades[0];
int currentMaxIndex = 0;
// i is back-limit that gets chopped off by one each time
for (int k = 1; k <= i; k++) {
if (currentMax < grades[k]) {
currentMax = grades[k];
currentMaxIndex = k;
}
}
// This is where im lost on how to call the min value
// Trying to mirror the one above but using it
// to show the minimum grade along with the name
for (int m = grades.length - 1; i > 0; i--) {
int currentMin = grades[0];
int currentMinIndex = 0;
// Min grades
for (int k = 1; k >= m; k++) {
if (currentMin < grades[m]) {
currentMin = grades[m];
currentMinIndex = m;
}
}
// After largest number is found, assign that number to i
// Im trying to have the final output show the min/max grade with who has it
// Would the MinIndex be assigned to a different variable?
grades[currentMaxIndex] = grades[i];
grades[currentMinIndex] = grades[m];
grades[i] = currentMax;
grades[m] = currentMin;
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
names[currentMaxIndex] = names[i];
names[currentMinIndex] = names[m];
names[i] = highName;
names[m] = lowName;
// This shows the name and grade for the highest number
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
// Unsure how to call this.
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
}
}
input.close();
keyboard.close();
}
}
Your code has multiple problems. First is with the 2 scanners that you are using for same System.in input stream and second you are using nested loops to find the min/max values which is totally unnecessary. Since the question is about finding the min/max so I will focus on that part only and for the scanner I would say remove the keyboard scanner and use only input scanner. Anyways, use the following code block to find the maximum and minimum grades with names:
int currentMaxIndex = 0;
int currentMinIndex = 0;
// Get min max
for (int i = 1; i<grades.length; i++) {
if (grades[currentMaxIndex]<grades[i]) {
currentMaxIndex=i;
}
if (grades[currentMinIndex]>grades[i]) {
currentMinIndex=i;
}
}
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
int currentMax = grades[currentMaxIndex];
int currentMin = grades[currentMinIndex];
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
The approach is quite simple. We first aasume that the first element in the grades array is min and max then we loop to the remaining elements from 1 to grades.length and compare the index min/max to the current index element values and accordingly change our min/max indices. If the current index value is greater than currentMaxIndex then we copy it to currentMaxIndex and same but opposite for currentMinIndex. So in the end we will have the highest and lowest value indices of grades array. The complete code is here https://ideone.com/Qjf48p
I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}
I am making a sample program that randomly assigns a certain amount of students from a certain amount of students to take a survey using arrays. Since a student can't be chosen two times, I need to figure out a way (the most efficient way, of course), to check and make sure that doesn't happen without using ArrayLists. Here is my current code (also if you have any suggestions on how to condense this code, I would love to hear them):
import java.util.*;
public class StudentsForSurvey {
public static void main(String[] argv) {
Scanner kb = new Scanner(System.in);
Random rndm = new Random();
int N = 0;
int slctd = 0;
while (N < 20) {
System.out.print("How many students are in the class?");
N = kb.nextInt();
System.out.println("Sorry, but School records say that there are at least 20 students `enter code here`in each classroom. Don't you know your own attendance!?");
}
while (slctd > 10 && slctd < 1) {
System.out.print("\nHow many students to randomly select?");
slctd = kb.nextInt();
System.out.println("Sorry, but at least 1 student and at most, 10 students, can `enter code here`participate in this survey. Didn't someone tell you this at orientation!?");
}
int[] stdntnums = new int[slctd - 1];
for (int i = 0; i < slctd - 1; i++) {
stdntnums[i] = i + 1;
}
int[] help = stdntnums;
System.out.print("Students selected are: ");
for (int x = 0; x <= slctd; x++) {
int rnd = rndm.nextInt(N) - 1;
for (int z = 0; z <= N; z++) {
System.out.print(stdntnums[rnd]);
}
}
}
}
Try this code. I had to do similar task then i had used it.
java.util.Random r = new java.util.Random();
java.util.Scanner s = new java.util.Scanner(System.in);
int arraylength = s.nextInt();
int students[] = new int[arraylength];
for(int i =0;i< arraylength;i++)
{
students[i]=i;
System.out.println(students[i]);
}
System.out.println("generated");
int no_of_selected_students = r.nextInt(arraylength);
int selected_students[] = new int[no_of_selected_students];
int last =no_of_selected_students;
for(int i=0;i<no_of_selected_students;i++)
{
int current = r.nextInt(last);
selected_students[i] = students[current];
students[current]= students[last];
last--;
System.out.println(selected_students[i]);
}
System.out.println("randomized");
What is not working is the sum part. Its not equaling the right number. Ex: user puts in 25 so the sum should be 75, but the program prints out 50.
My code:
import java.util.Scanner;
public class SumH4
{
public static void main(String[] args)
{
//define data
int x;
int sum;
//scanner is needed
Scanner sc = new Scanner(System.in);
//get user data and initialize variables
System.out.println("Please input a positive whole number.");
x = sc.nextInt();
sc.nextLine();
sc.close();
System.out.println();
sum = 0;
//do computation
for(int a = 0; a < x; a = a + 1)
{
if(a%5==0)
{
sum = sum + a;
}
}
//print results
System.out.println("Sum = " + sum);
}
}
You're not including the number itself that is input by the user. Simply change the for loop to the below so that the input x gets added:
for (int a = 0; a <= x; a = a + 1) {
Change
for(int a = 0; a < x; a = a + 1)
to
for(int a = 0; a <= x; a = a + 1)
At the moment you're not including 25, that only goes upto 24 i.e. a < x means "while a is less than x", then you want "while a is less than OR EQUAL TO x".
Your loop test should be <= (not <), also I suggest you define variables when you need them. Finally, you shouldn't close() a Scanner on System.in because that closes System.in and if you refactor your code you may cause yourself a lot of pain with that. So, I would change your method like
Scanner sc = new Scanner(System.in);
System.out.println("Please input a positive whole number.");
int x = sc.nextInt();
int sum = 0;
for (int a = 0; a <= x; a++) {
if (a % 5 == 0) {
sum += a;
}
}
// print results
System.out.println("Sum = " + sum);
What is wrong here? It's not printing test scores in descending order, nor am I getting a value for mean. Shows up 0.0
Her are the instructions that I was given:
This class will allow a user to enter 5 scores into an array. It will then rearrange the data in descending order and calculate the mean for the data set.
Attributes:
• data[]—the array which will contain the scores
• mean—the arithmetic average of the scores
Methods:
• Average—the constructor. It will allocate memory for the array. Use a for loop to repeatedly display a prompt for the user which should indicate that user should enter score number 1, score number 2, etc. Note: The computer starts counting with 0, but people start counting with 1, and your prompt should account for this. For example, when the user enters score number 1, it will be stored in indexed variable 0. The constructor will then call the selectionSort and the calculateMean methods.
• calculateMean—this is a method that uses a for loop to access each score in the array and add it to a running total. The total divided by the number of scores (use the length of the array), and the result is stored into mean.
• toString—returns a String containing data in descending order and the mean.
• selectionSort—his method uses the selection sort algorithm to rearrange the data set from highest to lowest.
import java.util.Scanner;
public class Average
{
private int[] data;
private double mean;
private int total = 0;
public Average()
{
data = new int[5];
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i < data.length; i++)
{
System.out.print("Enter score number " + (i + 1) + ": ");
data[i] = keyboard.nextInt();
}
}
public void calculateMean()
{
int i, s = 0;
for(i = 0; i < data.length; i++)
{
s = s + data[i];
}
mean = (double)s / (data.length);
}
public void selectionSort()
{
int maxIndex;
int maxValue;
for(int startScan = 0; startScan < data.length - 1; startScan++)
{
maxIndex = startScan;
maxValue = data[startScan];
for(int index = startScan + 1; index < data.length; index++)
{
if(data[index] > maxValue)
{
maxValue = data[index];
maxIndex = index;
}
}
data[maxIndex] = data[startScan];
data[startScan] = maxValue;
}
}
public String toString()
{
String output;
output = "The test scores in descending order are \n";
for(int i = 0; i < data.length; i++)
{
output = output + data[i] + " ";
}
output = output + "\nThe average is " + mean;
return output;
}
}
You need methods that return and take in values with your methods. Here is a little mock-up of your program to show what I mean:
public static void main(String... args)
{
System.out.println(calculateMean(getData()));
}
public static int[] getData()
{
data = new int[5];
Scanner s = new Scanner(System.in);
for (int i = 0; i < data.length; i++)
{
System.out.print("Enter score number " + (i++) + ": ");
data[i] = Integer.parseInt(s.nextLine());
}
s.close();
return data;
}
public static double calculateMean(int[] data)
{
int s = 0;
for (int i = 0; i < data.length; i++)
{
s += data[i];
}
return mean = (double) s / (data.length);
}
The getData() method gets all the information we need from the user, and then we take that data and we pass it right along to the calculateMean() method. This, in turn, spits out the average of all the scores for us. Then all we do is print that. I'll leave the rest up to you since this looks like homework.
Trial run:
Input: 4, 67, 3, 7, 3 (comma's indicate new line)
Output: 16.8
All you need is
public static void main(String[] args){
Average avg = new Average();
avg.selectionSort();
avg.calculateMean();
System.out.println(avg);
}
Everything is in place. I second #HeatfanJohn
It looks like you are not executing the calculateMean() method call first like that:
public static void main(String[] args) {
Average average = new Average();
average.calculateMean();
average.selectionSort();
System.out.println(average.toString());
}
You never make a call to calculateMean(), that is why the average is zero. In you main or where ever you create your instance of Average, you need to call calculateMean() before referencing Average.toString().