package chapter4; import java.util.*; public class WhileLoopPrints { private sta
ID: 3652245 • Letter: P
Question
package chapter4;import java.util.*;
public class WhileLoopPrints {
private static Scanner in;
public static void main(String[] args) {
{
int sum = 0;
for (int i = 0; i < 100; i = i + 2)
{sum += i;
}
System.out.println("The sum of all even numbers between 2 and 100 is: " +sum);
}
{
int sum = 0;
int sumOfSquares = 0;
for (int i = 100; i > 0; i-- )
{ sum = sum + i;
sumOfSquares = sumOfSquares + i * i;
}
System.out.println("The sum of all squares between 1 and 100 is: " +sumOfSquares);
}
System.out.println();
{ final double x = 2;
for (double y = 0; y <= 20; y++)
{ double powerOfTwo = Math.pow(x,y);
System.out.println("The of the powers of 2 from 0-20 are: " +powerOfTwo);
}
}
System.out.println();
{ Scanner in = new Scanner(System.in);
System.out.println("Please print an odd integer: ");
int a = in.nextInt();
System.out.println("Please print another odd integer that is larger than the first: ");
int b = in.nextInt();
int sum = 0;
for ( int number = a + 2; number < b; number = number + 2) // int number = a + 2 is so it does not include the first odd number
{
sum += number;
}
System.out.println("The sum of all odd numbers between the first and second integer are: " +sum);
in.close();
}
System.out.println();
{
Scanner in2 = new Scanner(System.in);
System.out.println("Please print an integer: ");
int i = in2.nextInt();
int sum = 0;
while (i != 0)
{ int x = i % 10;
if( i % 2 != 0)
sum = sum + x;
i = i / 10;
}
System.out.println("The sum of all odd numbers in the integer is: " +sum );
in2.close();
}
in.close()
}
}
(Something is wrong with the exception of main thread according to the error...
when I run it the whole program works until the last part which is supposed to print
the odd numbers of an integer)
Explanation / Answer
http://codepad.org/yAGz351F working code is here. The reason why this program is not working is because you are closing your in without ever opening it. Basically in the working code that i did, i took out your entire declaration of in because you never use it and there is no real need for it as in2 works just fine for what you are wanting to accomplish.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.