so I am working through MOOCfi and I am on the statistics problem. It's straightforward, just input numbers and return the sum of it until user enters -1. Here are the two classes:
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Statistics statistics = new Statistics();
while(true) {
int input = Integer.parseInt(scanner.nextLine());
if (input == -1) {
System.out.println("Count: " + statistics.getCount());
System.out.println("Sum: " + statistics.sum());
System.out.println("Average: " + statistics.average());
break;
}
statistics.addNumber(input);
}
}
}
Statistics.java
public class Statistics {
private int count;
private int sum;
public Statistics() {
this.count = 0;
}
public void addNumber(int number) {
this.count += 1;
this.sum += number;
}
public int getCount() {
return this.count;
}
public int sum() {
return this.sum;
}
public double average() {
return (1.0)*(this.sum/this.count);
}
}
My question is, for the line int input = Integer.parseInt(scanner.nextLine()). I wrote earlier:
if (Integer.parseInt(scanner.nextLine())
AND then
statistics.addNumber(Integer.parseInt(scanner.nextLine())
a few lines down, it whenever I ran it, it gave me some buggy inputs. Sometimes I would have to input -1 twice in order for it to stop, and by that point, the results were wrong. Specifically, entering 5,2,2 gave me a
Count: 2
Sum: 1
Average: 0.0
when it should be
Count: 3
Sum: 9
Average: 3.0
It seems like the if statement ALSO needs the int input rather than the Integer.parseInt(scanner.nextLine()) because putting that in there while keeping statistics.addNumber(input) yields a completely different answer if they were flipped. Is this some sort of weird java thing where assigning Integer.parseInt(scanner.nextLine()) to a int is different than just using it straight up?
Thank you!
Related
I'm trying to write a program that asks the user for numbers until the user enters -1. The program will then provide the sum of the numbers. The program should use a Statistics object to calculate the sum.
There are, however, specifications that come with this project. Those are
Do not modify the Statistics class in this part. Instead, implement the program for calculating the sum by making use of it.
public class Statistics {
private int count;
private int sum;
//private double average;
public Statistics() {
this.count = 0;
}
public void addNumber(int number) {
//sum += number;
count++;
}
public int getCount() {
return this.count;
}
public int sum(int user) {
this.sum = this.sum + user;
return this.sum;
}
public double average() {
double average;
average = (double) sum / this.count;
return average;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Statistics statistics = new Statistics();
System.out.println("Enter Numbers:");
int user=0;
while (user >= 0) {
statistics.sum(user = scan.nextInt());
}
System.out.println("Sum: " + statistics.sum(user));
}
}
If I (the user) input 4,2,5,2,-1... the program outputs Sum: 11. Why does it not equal Sum: 15?
Pay attention to this snippet:
int user=0;
while (user >= 0) {
statistics.sum(user = scan.nextInt());
}
System.out.println("Sum: " + statistics.sum(user));
you enter 4 -> .sum adds 4 to 0. sum=4; user = 4 (user>=0 true)
you enter 2 -> .sum adds 2 to 4. sum=6; user = 2 (user>=0 true);
you enter 5 -> .sum adds 5 to 6. sum=11; user = 5 (user>=0 true);
you enter 2 -> .sum adds 2 to 11. sum=13; user = 2 (user>=0 true);
you enter-1 -> .sum adds -1 to 13. sum=12; user =-1 (user>=0 false);
and your user variable is -1 at this time.
Finally you call statistics.sum(user) and that adds -1 to 12, which is 11.
This question is from mooc.fi's Java Programming Part 4 Programming exercise "Statistics".
In part 2 you should implement the class Statistics.
Below it contains a part that shows how this class is used:
public class Main {
public static void main(String[] args) {
Statistics statistics = new Statistics();
statistics.addNumber(3);
statistics.addNumber(5);
statistics.addNumber(1);
statistics.addNumber(2);
System.out.println("Count: " + statistics.getCount());
System.out.println("Sum: " + statistics.sum());
System.out.println("Average: " + statistics.average());
}
}
The program prints the following:
Count: 4
Sum: 11
Average: 2.75
Before moving to part 3, make sure your Statistics class produces the right output when used with that Main.
Once you got this working, move to the next part.
If I (the user) input 4,2,5,2,-1... the program outputs Sum: 11. Why
does it not equal Sum: 15?
It is happening because you are calling statistics.sum at two places (one, inside the while loop and one, after the while loop). The following code will help you trace how it is working:
import java.util.Scanner;
public class Statistics {
private int count;
private int sum;
// private double average;
public Statistics() {
this.count = 0;
}
public void addNumber(int number) {
// sum += number;
count++;
}
public int getCount() {
return this.count;
}
public int sum(int user) {
System.out.println("Got " + user);// Add this line for tracing
this.sum = this.sum + user;
return this.sum;
}
public double average() {
double average;
average = (double) sum / this.count;
return average;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Statistics statistics = new Statistics();
System.out.println("Enter Numbers:");
int user = 0;
while (user >= 0) {
statistics.sum(user = scan.nextInt());
}
System.out.println("Sum: " + statistics.sum(user));
}
}
A sample run:
Enter Numbers:
4
Got 4
2
Got 2
5
Got 5
2
Got 2
-1
Got -1
Got -1
Sum: 11
Ths, the final result has been calculated as 4 + 2 + 5 + 2 + (-1) + (-1) = 11
I tried different things in my code, but I always get errors.
The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user.
It must also return how many times the desire value is repeated on the array.
The errors are related to the counter and also some are in the main function.
I think I am not returning the counter value correctly.
This is my current code:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}
Multiple issues in your code.
public static int main(String[] args) should be public static
void main(String[] args)
findRepetition takes three arguments,
but you are passing two agruments
counter variable is not declared
Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.
static int findRepetition(int listOfValues[], int targetValue) {
int i;
int counter = 0;
for (i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == targetValue) {
counter = counter + 1;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int targetValue;
int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
System.out.println("Please enter the desire number to look for: ");
targetValue = input.nextInt();
int counter = findRepetition(listOfValues, targetValue);
if (counter != 0) {
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
} else {
System.out.println("The number " + targetValue + " is not contained in the array list");
}
}
You made your method accept three parameters.
static int findRepetition(int listOfValues[], int targetValue, int counter)
Ask yourself - do you want to "pass in a counter", or only return it? The instructions say the latter.
When you call this method, you are not providing the correct inputs.
findRepetition(targetValue, counter);
What about the listOfValues? You want to findReptition on listOfValues for targetValue, right? So provide the correct parameters into that method call.
Again, you likely do not need the counter passed-in. Because Java is always pass-by-value
Rather, you want to return counter, as you have written. You are looking for this.
int counter = findRepetition(listOfValues, targetValue);
Fixing the remainder of the code is a learning exercise.
You are not calling findRepetition() with required parameters, findRepetition method takes 3 arguments, but you are passing only 2 arguments.
I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;
I have a program (written in Java) that when it reaches a for or a while loop, it stalls for about 2 seconds then stops completely. Here is the code:
import javax.swing.*;
public class numberCruncher
{
public static int number,guess,x;
public static void main(String[] argv)
{
number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):");
System.out.print("1");
test();
}
public static void test()
{
boolean correct = false;
System.out.print("2");
//while(correct=false)
for(x=0;x>999999999;x++)
{
//x++;
System.out.print("3");
guess=cleanUsage.random(0,99999);
System.out.print("4");
System.out.println(" "+guess);
if (guess==number)
{
System.out.println();
System.out.println("Correct number guessed in "+x+" tries");
//correct = true;
}
}
}
public static int enterIntGUI(String prompt)
{
String tempString = JOptionPane.showInputDialog(prompt);
int temp = Integer.parseInt(tempString);
return temp;
}
}
You can see that I have comments for the while loop stuff. Also, I have put in 4 println statements where I thought it would be getting stuck, and it printed 1 and 2, but not 3. Here is the portion of my cleanUsage class that contains the random number generator:
public static int random(int min, int max)
{
int range = max - min + 1;
int number = (int) (range * Math.random() + min);
return number;
}
I have asked some other people and they could not figure it out. If you could help me out, that would be great.
It doesn't print 3 or 4 because the condition x>999999999 is initially false so that for loop is never entered. I assume you meant <.
Also note that you can use break rather than correct = true to exit a loop.
import javax.swing.*;
public class numberCruncher
{
public static int number,guess,x;
public static void main(String[] argv)
{
number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):");
System.out.print("1");
test();
}
public static void test()
{
boolean correct = false;
System.out.print("2");
//while(correct==false) // equality test, not assignment
for(x=0;x<999999999;x++) //2nd argument is continue while false
{
//x++;
System.out.print("3");
guess=cleanUsage.random(0,99999);
System.out.print("4");
System.out.println(" "+guess);
if (guess==number)
{
System.out.println();
System.out.println("Correct number guessed in "+x+" tries");
//correct = true;
}
}
}
public static int enterIntGUI(String prompt)
{
String tempString = JOptionPane.showInputDialog(prompt);
int temp = Integer.parseInt(tempString);
return temp;
}
}
I am in the middle of an exercise on arrays and I am currently stuck on one of the variations in which
I have to use an Array (no arraylists) to gather user input with a
max number of 100 inputs and the inputs must stop if a negative
number is inserted.
The program then prints each value input by the user on a separate
line with the "Above", "Below", or "EqualTo" relating to the average
of the inputs.
Issue :- I am currently stuck in how I am supposed to get the value of the inputs from the load method into the correct spots on the print method. The program will compile but will only return an average1 equal to zero. Any help is appreciated, I just can't use an arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}
That's because you are not saving the average to the global variable average1 but to a local variable. That is why average1 returned by getAverage() equal to zero.
Change the below line in load() method from
double average1 = sum / used;
to
average1 = sum / used;