What did I do wrong? I'm really not sure what else to try or where my mistake is. Thanks for any help. It's supposed to calculate the sum of integers between two numbers, e.g. between 3 and 6 it would be 3 + 4 + 5 + 6
import java.util.Scanner;
public class TheSumBetweenTwoNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("First:");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Second:");
int max = Integer.parseInt(reader.nextLine());
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
System.out.println("Sum is " + sum);
}
}
Why all this you need just a piece of code like this :
public static void main(String args[]) {
int min = 3, max = 6, sum = 0;
for (int i = min; i <= max; i++) {
sum += i;
}
System.out.println(sum);
}
With while loop it should be :
...
int i = min;
while (i <= max) {
sum += i;
i++;
}
...
You don't need to find a difference and loop over it, just running a loop from n to max will do. Also, you need to add the value to sum (+=) instead of assigning a value to it (=, which overwrites previous value)
Try this:
int i = n;
while (i <= max) {
sum += i;
i++;
}
You're overwriting the previous sum value with the most recent n + (n + 1), instead of accumulating the previous sum. Also, your loop is one iteration short. Try this:
int sum = 0;
for (int i = n; i <= max; i++) {
sum += i;
}
System.out.println("Sum is " + sum);
Change this snippet
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
In
int sum = 0;
int i = n;
while (i <= max) {
sum = sum + i;
i++;
}
You made it a little bit overcomplicated. All you really need is a for loop that runs from n to max that adds up the incrementing variables:
int sum = 0;
for(int i = n; i <= max; i++){
sum += i;
}
Related
I'm getting an error message (java.util.NoSuchElementException) in thread main when attempting to compile the following code with the input 3, then 4, 5, and 7. I've tried to tweak the code, but there's something I'm missing. I was thinking it may be due to my use of arrays since I am just learning how to use those, but I've tried to look closely at them and I didn't see anything I did wrong, but I definitely missed something. Any help would be appreciated. Thanks!
import java.util.Scanner;
public class ArrayMethods2 {
public static int[] findMinAndMax(int[] x) {
int i;
int min = x[0];
int max = x[0];
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
int [] minAndMax = new int[2];
minAndMax[0] = min;
minAndMax [1] = max;
return minAndMax;
}
public static double averageWithDrop(int[] x) {
int i;
int min = x[0];
int minIndex1 = 0;
int minIndex2 = 0;
int sum = 0;
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
minIndex1 = i;
}
}
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
if (i != minIndex1)
minIndex2 = i;
}
}
for (i = 0; i < x.length; i++) {
if (i == minIndex1) {
sum = sum + 0;
}
else if (i == minIndex2) {
sum = sum + 0;
}
else {
sum = sum + x[i];
}
}
double average = sum / (x.length - 2);
return average;
}
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? (must be at least 3) ");
int userValue = scnr.nextInt();
System.out.println(userValue);
while (userValue < 3) {
System.out.println("Invalid value, must be at least 3. Please try again ");
userValue = scnr.nextInt();
System.out.println(userValue);
}
int x = 0;
int indexVal;
int [] userArray = new int [userValue];
while (x <= userValue) {
System.out.print("Enter value for index " + x + ": ");
indexVal = scnr.nextInt();
System.out.println(indexVal);
userArray[x] = indexVal;
x++;
}
int [] minAndMaxVal = new int [2];
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
double avg = averageWithDrop(userArray);
System.out.println("Average excluding two lowest values: " + avg);
}
}
Running your code, I did not get any NoSuchElementException, however I got IndexOutOfBoundsException. Check the class your are running.
Please remember arrays are 0 based.
In the main method change while (x <= userValue)to while (x < userValue)
Again, arrays are 0 based, change:
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
to
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);
There are few problems in the code :
Update this (x <= userValue) to (x<userValue) , else it will give array index out of bounds exception
Start the for loop in minMaxFunction from 1 , since you have already stored the value of arr[0] to min and max like below . This is just an optimization in the code.
for (i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
This line in main method should have index 0 and index 1 . There is no index 2 since you have declared the array of length 2 , else it will give array index out of bounds exception
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);
I'm stuck trying to calculate the average when I generate 3 random integers between 1 and 20. I have to round the average to int and repeat it 10000 times. When I test my program repeating 2 times, I am getting the output of:
Number is :18
Number is :14
Number is :2
sum is: 34
Average is: 11
Number is :13
Number is :3
Number is :6
sum is: 56
Average is: 18
However, the average should be the average of just the 3 numbers. Here, the second loop adds the sum of the first loop to the sum of the second making the average wrong (Sum:34+22=56). I want it to be 22 so the average for that would be 7. I notice the problem might be this line, sum += n; , but I don't know another way to add the 3 number for each loop to get the average.
package Histogram;
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
final int N = 2;
Random rand = new Random();
int n;
int average;
int sum = 0;
for (int a = 0; a < N; a++) {
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
}
}
}
Your sum += n; inside the second for loop keeps on incrementing the value of sum (even the older sum values from loop). Thus you need to reset the value of sum to 0 every time at the begineeing the first loop.
for (int a = 0; a < N; a++) {
sum = 0;
//rest of the code
You must clean the sum variable after the first loop:
//..
int sum;
for (int a = 0; a < N; a++) {
sum = 0; // -------> Here it is necessary to be clean for the next iteration
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
//...
}
the average should be the average of just the 3 numbers. Here, the
second loop adds the sum of the first loop to the sum of the second
making the average wrong (Sum:34+22=56). I want it to be 22 so the
average for that would be 7
One approach is to reset the value of sum after you've printed the sum and average to the console.
Example:
int n;
int average;
int sum = 0;
for (int a = 0; a < N; a++) {
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
sum = 0;
}
or to make life easier you can make the variable sum local within the loop so that at each iteration the value of sum will reset to default value:
Example:
int n;
int average = 0;
for (int a = 0; a < N; a++) {
int sum = 0;
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
}
If you want the total sum I suggest adding a second iterationSum variable to add up the 3 numbers. Something like:
for (int a = 0; a < N; a++) {
int iterationSum = 0;
for (int i = 0; i < 3; i++) {
...
iterationSum += n;
}
average = iterationSum / 3;
...
}
If you don't care about the total sum just reset you sum to 0 in each iteration:
for (int a = 0; a < N; a++) {
sum = 0;
...
}
public static void main(String[] args) {
final int N = 2;
Random rand = new Random();
int n;
int average;
int sum = 0;
for (int a = 0; a < N; a++) {
sum=0;// this makes the trick
for (int i = 0; i < 3; i++) {
n = rand.nextInt(20) + 1;
System.out.println("Number is :" + n);
sum += n;
}
average = sum / 3;
System.out.println("sum is: " + sum);
System.out.println("Average is: " + average);
}
}
I am supposed to create a perfect number class using the following pseudocode:
For i from 2 to “very large”,
For j from 2 to √i,
if (j evenly divides i),
accumulate the sum j and i/j
if √i is an integer
subtract √i ... you added it twice
if the sum of divisors == i
Print the number ... it’s perfect!
So here is my version. It runs, but it doesn't do what I want at all. It just runs and produces nothing as an output. Can someone tell me what is wrong with my program? It's bothering me so much.
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
double sum = 0
double newsum = 0;
for (int i = 2; i < 1000000; i++) {
for (int j = 2; i<Math.sqrt(i); j++){
if (i%j==0){
sum = j + (i%j);
}
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a perfect number");
}
}
}
}
}
Few mistakes according to the algorithm:
sum = j + (i%j); should be changed to sum = j + (i/j);
This piece:
if (Math.sqrt(i)==(int)i){
newsum = sum - Math.sqrt(i);
}
if (sum == 0) {
System.out.println(sum + "is a prime number");
}
Should be under upper "for"
Math.sqrt(i)==(int)i would never be true unless i is 1. If you want to check this that way you should write Math.sqrt(i)==((int) Math.sqrt(i))
There are much more errors, the simplest way to do it is:
double sum = 0;
for (int i = 1; i <= 10000; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (i == sum) {
System.out.println(sum + " is a prime number");
}
sum = 0;
}
Your code contains several mistakes. Here is the corrected code, commented with the changes.
// newsum isn't needed; declare sum to be int to avoid floating-point errors
int sum = 0;
for (int i = 2; i < 1000000; i++) {
// Start with 1; every natural number has 1 as a factor.
sum = 1;
// Test if j, not i, is less than the square root of i.
for (int j = 2; j <= Math.sqrt(i); j++){
if (i % j == 0){
// Add to sum; don't replace sum. Use i / j instead of i % j.
sum = sum + j + (i / j);
// Move test inside this if; test if j is square root of i
if (j*j == i){
// I used j because we know it's the square root already.
sum = sum - j;
}
}
// Move print outside of inner for loop to prevent multiple
// printings of a number.
// Test if sum equals the number being tested, not 0.
if (sum == i) {
// Space before is
System.out.println(sum + " is a perfect number");
}
}
}
Output:
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
public static void main(String[] args){
int min = 2;
int max = 1000000;
int sum = 0;
for (; min <= max; min++,sum = 0) {
for (int e = 1; e < min; e++)
sum += ((min % e) == 0) ? e : 0;
if (sum == min){
System.out.println(sum);
}
}
}
for(n=1;n<=number;n++){ //calculates the sum of the number.
int i=1;
int sum = 0;
while(i<n){
if(n%i==0)
sum+=i;
i++;
}
if(sum==n){ //if the sum is equal to its sum :
System.out.print(n+": ");
for (int j = 1;j<n;j++){
if(n%j==0){
System.out.print(j+" ");
}
}
System.out.println();
}
}
Here is the simplest and easiest form you can write a program for perfect number....this code gives perfect number within 25 ...you can change as you want
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
int n,i,j,count=0;
for(i=2;i<=25;i++) {
for(j=1;j<=i;j++) {
if(i%j ==0) /*count increments if a reminder zero*/ {
count++;
}
}
/*since a perfect number is divided only by 1 and itself
if the count is 2 then its a prime number...*/
if(count==2)
System.out.println(i);
count=0;
}
return 0;
}
}
According to the pseudocode you want to move the second and third if test outside of the inner loop
for (int i = 2; i < 1000000; i++) {
double iroot = Math.sqrt(i);
int sum = 1;
for (int j = 2; j <= iroot; j++){
if (i % j == 0){
sum = sum + j + i / j;
}
}
if (iroot == (int) iroot) {
sum = sum - iroot;
}
if (sum == i) {
System.out.println(sum + "is a perfect number");
}
}
Thanks for watched
public boolean testPerfect(int n){
int i=1;
int sum=0;
while(i<n){
if(n%i==0)
{
sum+=i++;
}
else{
i++;}
}
if (sum==n){
return true;
}
return false;
}
This is a question from the book Introduction to Java by Y Daniel Liang:
Convert for loop statement to a while loop and do-while loop?
int sum = 0;
for (int i = 0; i <= 7; i++)
sum = sum + i;
I am pretty confused on how to convert it to a do-while loop. What am I supposed to do? Please see my code below.
public class Convert_forLoop_toWhileLoop {
public static void main(String[] args) {
int sum = 0;
int i = 0;
do {
sum = sum + i;
System.out.println(sum);
i++;
} while(i <= 7);
}
}
Depending on how scrupulous you wanna be, a "more" equivalent do-while-loop of your for-loop example would be:
int sum1(int n) {
int sum = 0;
for (int i = 0; i <= n; i++) {
sum = sum + i;
}
return sum;
}
int sum2(int n) {
int sum = 0;
{
int i = 0;
if (i <= n) {
do {
sum = sum + i;
i++;
} while (i <= n);
}
}
return sum;
}
Note I wrapped your example in sum1 (passing sum1(7) is equivalent to your case).
For those who really want to split hairs -- note Java doesn't necessarily compile the 2 functions above into the same bytecode (at least when I tested it, to my surprise). 2 extra bytecode instructions for sum2 (20 vs. 22). Just something interesting I noticed.
Like this:
int sum = 0;
int i = 0;
do {
sum += i;
i++;
} while (i <= 7);
System.out.println("The sum of 0 thru " +i + " is:" + sum);
Your answer doesnt support the case where i initial value is >= number of loops.
you need to first check the condition.
while (i <= 7) {
sum+=i;
// at the last statement increase i
i++
}
System.out.println(sum);
I am new here. I am trying to solve this exercise Problem 18 just for reinforcing my solving skills. I've already coded the answer. The task asks for "How many of the primes below 1,000,000 have the sum of their digits equal to the number of days in a fortnight?" (a fortnight is 14 days). My answers is 16708, but it is wrong. I hope you can help me. I don't know what my error is. I have 2 methods, 1 for generating the primes, and another for counting the digits of each prime.
This is my code:
import java.util.ArrayList;
import java.util.List;
public class Problema18 {
public static void main(String args[]) {
ArrayList<Integer> num = primes();
System.out.println(num);
count(primes());
}
public static ArrayList<Integer> primes() {
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= 1000000; i += 2) {
boolean isPrime = true;
int stoppingPoint = (int) (Math.pow(i, 0.5) + 1);
for (int p : primes) {
if (i % p == 0) {
isPrime = false;
break;
}
if (p > stoppingPoint) { break; }
}
if (isPrime) { primes.add(i); }
}
// System.out.println(primes);
return (ArrayList<Integer>) primes;
//System.out.println(primes.size());
}
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
if (sum == 14) { count++; }
}
System.out.println(sum);
}
System.out.println(count);
}
}
You should check whether sum == 14 outside the inner for loop. What happens now is that you also count those primes for which the sum of digits is larger than 14 but the sum of the digits in some prefix of the prime is equal to 14.
This part...
if (sum == 14) {
count++;
}
should be outside the inner for-loop - i.e. you want to do it each time you pass through the i for-loop, but not each time you pass through the j for-loop.
Like this:
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
}
System.out.println(sum);
if (sum == 14) {
count++;
}
}
System.out.println(count);
}