Logical error in loop program - java

import java.util.Scanner;
public class Unit2Err2{
public static void main( String[] args ){
Scanner scan = new Scanner(System.in);
double sum = 0;
double count = 0;
double in = scan.nextDouble();
while (scan.nextDouble()!= 0){
sum = sum + in;
count++;
}
double avg= sum/count;
System.out.println("The average is " +avg);
}
}
Input: 5 4 3 0 6 4 3
In particular I don't have any errors, I did have a error which said:
incomparable types: boolean and int.
But I fixed it, my issue now is that the average should be 4 instead of 5. I'm wondering where the error is in this, I have tried rearranging it so my average comes out to 4 , but then I often end up with the same error as above.

import java.util.Scanner;
public class Unit2Err2{
public static void main( String[] args ){
Scanner scan = new Scanner(System.in);
double sum = 0;
double count = 0;
double in ;
while ( (in = scan.nextDouble())!= 0){
sum = sum + in;
count++;
}
double avg= sum/count;
System.out.println("The average is " +avg);
}
}
when you first use nextDouble here double in = scan.nextDouble(); it has read a value from the terminal.

You need to re-assign in at each iteration:
while ((in = scan.nextDouble()) != 0){
sum += in;
count++;
}

The program stops and waits for input when it sees the "scan.nextDouble()" statement. Having two in a row is going to read both 5 and 4 without doing anything with the values.
The current code assigns the first input of 5 to the variable in. After that, in is never assigned the value. So 5 is being added each loop iteration.

Related

unexpected type Required: Variable Found: Value

import java.util.*;
public class happy_number
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = in.next();
for (int i = 0; i < num.length(); i++){
double index = num.charAt(i);
(double)index = Math.pow((double)i,2);
System.out.println(index);
}
}
}
For some reason, the second line in the for loop is returning as unexpected type– required: variable found: value. Any insight?
error: image of the error
It doesn't continue to ask you for an input. What is happening here is that the execution get's struck in an infinite loop, for certain types of inputs (in this case non-magic numbers).
For Eg.:
Let's take the example 44, below will be the values for each iteration in the for loop.
num
num1
num2
Start
44
-
-
After 1st iteration
8
4
4
After 2nd iteration
8
8
0
After 3rd iteration
8
8
0
…
…
…
…
We can see that the execution get's struck in the loop.
You have to exit out of the loop when you get such inputs.
One way to exit out of the loop is to add a condition in the for loop.
Another way is to add an if statement inside the for loop, and exit out of the loop based on the condition.
You have to decide what condition you should use in order to exit the loop, based on your problem statement.
Look on to the loop and the value populated inside. There is no breaking condition found and the correct test for a magic number:
A simple code:
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int n = num;
while (n > 9) {
int sum = 0;
while (n != 0) {
int d = n % 10;
n /= 10;
sum += d;
}
n = sum;
}
if (n == 1)
System.out.println(num + " is Magic Number");
else
System.out.println(num + " is not Magic Number");
}

Finding the sum of all elements of a sequence, ending with the number 0 using do-while loop in Java

I am a beginner. I appreciate if someone solves my problem in simple way in Java.
Problem:
Find the sum of all elements of a sequence, ending with the number 0.
The number 0 itself is not included into the sequence and serves as a sign of cessation.
Sample Input:
3
6
8
0 and
Sample Output:
17
I am writing following program:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
do {
sum += scanner.nextInt();
} while (scanner.nextInt() != 0);
System.out.println(sum);
}
And What I get is as following:
Input:
3
6
8
0
Output:
11 <---it should come out as 17.
Please figure out where the code is wrong.
The problem with your code
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
do {
sum += scanner.nextInt(); // consuming an int from keyboard with nextInt()
} while (scanner.nextInt() != 0); // consuming another int from keyboard with nextInt()
System.out.println(sum);
for input 3 6 8 0
sum += scanner.nextInt(); //this nextInt() consumes 3 now sum has 3
scanner.nextInt() != 0 // this nextInt() consumes 6 but does not add to sum now sum has 3 only the 6 is ignored
sum += scanner.nextInt(); // same here this consumes 8 and add to sum now sum has 11 which is the output
scanner.nextInt() != 0 // this nextInt() consumes 0 which fails the condition
In short you are ignoring every second input
The fix
Scanner scanner = new Scanner(System.in);
int sum = 0;
int num = 0;
while((num = scanner.nextInt()) != 0) { // nextInt() is called only once and value is cashed in num
sum += num; // add this num to sum
}
System.out.println(sum); // prints 17 as expected
Please try below code
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int checker = 0;
do {
checker = scanner.nextInt();
sum += checker;
} while (checker != 0);
System.out.println(sum);
}
}
In your code value coming from scanner.nextInt() in while loop is being missed to be added. That's causing a issue

for some reason, when i compile and try to run the program, the sum doesn't add up right

public static void main (String[] args) {
double sum = 0;
int count = 0;
double userEnterNumber = 0;
double min = 0;
double max = 0;
double average = 0;
System.out.println(" Input a number, type a non-numerical value to exit: ");
Scanner in = new Scanner(System.in);
userEnterNumber = in.nextDouble();
while ( in.hasNextDouble())
{
userEnterNumber = in.nextDouble();
if (userEnterNumber>0) {
sum = sum + userEnterNumber;
count ++;
average = sum/count;
if (userEnterNumber >=max){
max = userEnterNumber;
}
}
}
System.out.println(" Sum: "+sum);
System.out.println(" Count: "+count);
System.out.println(" Average: "+average);
System.out.println(" Minimun: "+min);
System.out.println(" Maximum: "+max);
}
I am trying to figure whats going on with my program. Whenever I run it, it gives me wrong sum and wrong count. How can I fix it? How can i also add minimum in here? Thanks
Read through your program. You are calling this twice:
userEnterNumber = in.nextDouble();
before your 1st stat calculation takes place.
Effectively, this means the first Double you enter is skipped. Do the output numbers make sense now?
In the future, try running your program in the debugger and determining whether each variable holds the correct/expected value at each step.

output blank--Java program to calculate average of array

I am writing a program that takes 10 floating point numbers as inputs, and displays the average of the numbers followed by all of the numbers that are greater than the average. I am using a method that takes an array of doubles as a parameter and returns the average of the data in the array. However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code. Thank you.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}
to answer the main question...
However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code.
public static void main(String[] args) {
new Average().average(new double[10]);
}
Or maybe you are thinking something like this...
public static void main(String[] args) {
double[] numbers = {2,3,4,5,6,4,3,2,1,3};
new Average().average(numbers);
}
A output run from above (with the doubles given):
Please enter 10 floating-point numberes.
If more than 10 values are entered, the numbers following 10 are ignored.
If less than 10 numbers are entered, the program will wait for you to enter 10.
2
3
3
4
1
2
3
4
5
1
Average value of your input is: 0.2
Average value of your input is: 0.5
Average value of your input is: 0.9
Average value of your input is: 1.4
Average value of your input is: 2.0
Average value of your input is: 2.4
Average value of your input is: 2.7
Average value of your input is: 2.9
Average value of your input is: 3.0
Average value of your input is: 3.3
1.0
1.0
1.0
Press any key to continue . . .
If you have question about the code itself, then it would be better to create a new question or edit it to make it more clear.
Good luck with your coding.
Your method average() takes an array of doubles, but then retrieves an other array from standard input. That doesn't make sense.
Either get the doubles and pass them to the method, or don't pass them to the method and get them from standard input.
What you need to do is create an instance of Average class in your main method and call the average() method.
Why parse double array in your average() method when you take the input from user?
well,you are using a non static method "average()" for your task which needs an instances of the class to run which are not creating anywhere.so there are only two options:-
#1.create an instances of your class then call it.
public static void main(String... s)
{
Average obj=new Average();
obj.average();
}
#2.make "average()" a static method by adding static keyword.
public static double average()
{
//your code.....
}
public sttatic void main(String... s)
{
average();
}
your dont need to keep an argument in your method.

Adding the first ten odd numbers - incorrect output

I'm writing a program that adds the first ten odd numbers, and gets the sum at the end.
Here is my code so far. My code reads the odd number in a list of 10 numbers. I want my code to be able to read 10 odd numbers even if there are more than 10 numbers entered. I know the problem is i < 10, which makes the program stop after the 10th number.
import java.util.Scanner;
public class question14
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i = 0;
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
}
}
Wrap it in a while loop instead.
While oddnumbers < 10 ask for a new number.
int i = 0
while(i < 10) {
odd = keyboard.nextInt();
if (odd % 2 != 0) {
sum = sum + odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is " + sum);
EDIT:FULL CODE
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author stevengreen22
*/
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int input;
int inputCount = 0;
while (i < 10){
//Having this inside the while loop prompts the user every time.
System.out.println("New number?");
input = scan.nextInt();
inputCount++;
if(input % 2 == 1){
sum += input;
i++;
}
}
System.out.println("sum: "+sum);
System.out.println("Number of odds:" + i);
System.out.println("Numbe of inputs: " +inputCount);
System.out.println("Average cos I miss typing sout tab:" + (inputCount/sum));
}
}
The principle thing is that you don't know how many numbers the user is going to enter into the program, so you want to use a while loop instead of a for loop.
One chooses a for loop when they know how many elements they want to iterate over; one chooses a while loop when they don't know how many elements they'll need to iterate over.
You'll need to define another variable called counter outside of the loop, and use this as your loop variable constraint.
while(counter < 10) {
// loop
}
You'll also need to update counter whenever you encounter an odd value.
This should work
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int odd,sum=0;
System.out.println("enter numbers");
int i=0;
while (i<10){
odd=keyboard.nextInt();
if (odd%2!=0){
sum=sum+odd;
i++;
}
}
System.out.println("The sum of first 10 odd numbers is "+sum);
}
Just replace your for loop with a while loop and track the number of odd numbers in an integer:
int oddNumberCount = 0;
int inputNumber;
while(oddNumberCount<10)
{
inputNumber = keyboard.nextInt();
if(inputNumber%2!=0)
{
sum = sum+inputNumber;
oddNumberCount++;
}
}

Categories

Resources