Why do i get Exception in thread "main" java.util.NoSuchElementException? - java

I'm new at this, and having some trouble with my code. The thing is, it works, but i keep gettingthis "Exception in thread "main" java.util.NoSuchElementException" when i check my exercise in jet brains. But in my IDE it does work. This is the exercise =
"Write a program that reads two numbers a
a
and b
b
from the keyboard and calculates and outputs to the console the arithmetic average of all numbers from the interval [a;b]
[
a
;
b
]
, which are divisible by 3
3
.
In the example below, the arithmetic average is calculated for the numbers on the interval [−5;12]
[
−
5
;
12
]
. Total numbers divisible by 3
3
on this interval 6
6
: −3,0,3,6,9,12
−
3
,
0
,
3
,
6
,
9
,
12
. Their arithmetic average equals to 4.5"
The program works and returns the 4.5.
This is my code:
int a = in.nextInt();
int b = in.nextInt();
double divisible = 0;
int sum = 0;
double num =0;
for (double i = a; i<b; i ++) {
num = in.nextInt();
if (num%3==0) {
divisible = divisible +1;
sum += num;
}
}
double result = sum/divisible;
System.out.println(result);
Hope u can help me because I really wanna improve my skills and keep learning. Thank you for your time.

Try:
int a = sc.nextInt();
int b = sc.nextInt();
double count = 0;
double sum = 0;
for (double i=a; i<=b; i++) {
// Check if number is divisible by 3
if (i % 3 == 0) {
// Count total numbers
count += 1;
// Calculate sum
sum += i;
}
}
double result = sum / count;
System.out.println("Average: " + result);
Output:
Explanation:
Removed num = in.nextInt(); as i in for (double i=a; i<=b; i++) will get all numbers between a and b.
Replaced sum += num; with sum += i;.

Related

Java:Three digit Sum - Find out all the numbers between 1 and 999 where the sum of 1st digit and 2nd digit is equal to 3rd digit

Problem statement: Three digit sum - Find all the numbers between 1 and 999 where the sum of the 1st digit and the 2nd digit is equal to the 3rd digit.
Examples:
123 : 1+2 = 3
246 : 2+4 = 6
Java:
public class AssignmentFive {
public static void main(String[] args) {
int i=1;
int valuetwo;
int n=1;
int sum = 0;
int valuethree;
int valueone = 0;
String Numbers = "";
for (i = 1; i <= 999; i++) {
n = i;
while (n > 1) {
valueone = n % 10;/*To get the ones place digit*/
n = n / 10;
valuetwo = n % 10;/*To get the tens place digit*/
n = n / 10;
valuethree = n;/*To get the hundreds place digit*/
sum = valuethree + valuetwo;/*adding the hundreds place and
tens place*/
}
/*Checking if the ones place digit is equal to the sum and then print
the values in a string format*/
if (sum == valueone) {
Numbers = Numbers + n + " ";
System.out.println(Numbers);
}
}
}
}
I got my result :
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000001
100000000011
1000000000111
10000000001111
100000000011111
1000000000111111
10000000001111111
100000000011111111
1000000000111111111
Process finished with exit code 0
The result is not showing the actual result like it should be which should show values like: 123, 246 (Please refer to the problem statement above.)
Please let me know what seems to be the issue with the code and how to tweak it.
Don't know what you're trying to do with that while loop, or why you are building up a space-separated string of numbers.
Your code should be something like:
for (int n = 1; n <= 999; n++) {
int digit1 = // for you to write code here
int digit2 = // for you to write code here
int digit3 = // for you to write code here
if (digit1 + digit2 == digit3) {
// print n here
}
}
So basically your question is how to calculate the numbers, right?
My first hint for you would be how to get the first, second and third value from a 2 or 3 digit number.
For example for 3 digits you can do int hundretDigit = (n - (n % 100)) % 100. Of course this is really inefficient. But just get code working before optimizing it ;)
Just think about a way to get the "ten-digit" (2nd number). Then you add them and if they equal the third one you write System.out.println(<number>);
EDIT:
For 2 digit numbers I will give you the code:
if(i >= 10 && i <= 99) {
int leftDigit = (i - (i % 10)) / 10;
if(leftDigit == (i % 10)) {
//Left digit equals right digit (for example 33 => 3 = 3
System.out.println(i);
}
}
Try again and edit your source code. If you have more questions I will edit my (this) answer to give you a little bit more help if you need!

Calculating sum of odd numbers between two user inputs

I am trying to calculate the sum of the odd numbers between two user inputted numbers.
This is the code I have so far:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
int sum = 0;
for (int i = num1; i <= num2; i += 2) {
sum = sum + i;
}
System.out.print(sum);
}
}
When I input 3 and 11, it outputs 35, which is correct.
However, with 4 and 20, it outputs 108, which is not correct. It should instead be 96.
Where have I gone wrong in the code?
You need to check if the first number is even or odd first, because if it is even, it is going to sum the even numbers instead of odd ones since you are increasing "i" by 2 after every iteration. Try adding the line below before the for loop.
if(num1%2==0){num1++);
Explanation
Your loop sums the even numbers if you start with an even number.
Check your code:
for (int i = num1; i <= num2; i += 2)
Assume num1 is even, e.g. 4. Then your loop starts with i = 4. And then you continue with += 2, so you end up with 6, 8, 10, ..., i.e. the even numbers.
Solution
You can simply fix it by patching num1 before your loop.
// Put this before your loop
if (num1 % 2 == 0) { // checks if num1 is even
num1++;
}
This way you will start with 5 then, and then get 7, 9, 11, ....
To sum a range of numbers:
Take the average of the first number and the last number, and multiply by the number of numbers.
But, first you need to make sure you lower and upper bounds are odd numbers. This is actually what is the problem with the code in the question.
Once that is done, calculate the average number, and the number of numbers:
public static long sumOddNumbers(int min, int max) {
long minOdd = (min % 2 == 1 ? min : min + 1); // Round up to odd number
long maxOdd = (max % 2 == 1 ? max : max - 1); // Round down to odd number
if (minOdd > maxOdd)
return 0;
// average = (minOdd + maxOdd) / 2
// count = (maxOdd - minOdd) / 2 + 1
// sum = count * average
return ((maxOdd - minOdd) / 2 + 1) * (minOdd + maxOdd) / 2;
}
Test
System.out.println(sumOddNumbers(3, 11)); // prints: 35
System.out.println(sumOddNumbers(4, 20)); // prints: 96
This can be done easily with a mathematical formula. But based on your question I presume you want to use a loop so here goes.
An odd number has the low order bit set to 1.
If the number is already odd, resetting that bit has no effect so it is still odd.
But setting that bit for an even number makes it the next higher odd number.
So use the bitwise OR operator.
3 | 1 = 3
4 | 1 = 5
And do the following:
int start = 4;
int end = 20;
int sum = 0;
for (int i = (start | 1); i <= end; i += 2) {
sum += i;
}
System.out.println(sum);
If you want to use streams in Java 8+ you can do it this way.
int sum = IntStream.rangeClosed(start, end).filter(i -> i & 1 == 1).sum();
And the formula I was talking about is the following, derived using simple series summation.
For ints, start and end
start |= 1; // ensure start is next odd number
end = (end | 1) - 2;// ensure end is last odd - 2
int sum = ((start + end) * ((end - start) / 2 + 1)) / 2;
If the two numbers are natural numbers, you can apply the formula:
Sum of odd natural numbers from m to n = sum of natural odd numbers up to n - sum of natural odd numbers up to m
= (n/2)^2 - (m/2)^2
where n is an even number or the next even number in case it is an odd number
In the program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = Math.abs(s.nextInt());
System.out.print("#2: ");
int num2 = Math.abs(s.nextInt());
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
num1 = 5;
num2 = 15;
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
num1 = 5;
num2 = 16;
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
num1 = 6;
num2 = 15;
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
}
static int sumNaturalOddOfRange(int num1, int num2) {
if(num2%2==1)
num2++;
return (int)(Math.pow(num2 / 2, 2) - Math.pow(num1 / 2, 2));
}
}
A sample run:
#1: 10
#2: 20
Sum of natural odd numbers from 10 to 20 = 75
Sum of natural odd numbers from 5 to 15 = 60
Sum of natural odd numbers from 5 to 16 = 60
Sum of natural odd numbers from 6 to 15 = 55
**Here is the answer**
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
int sum = 0;
if (num1%2==0) {
num1++;
}
for (int i = num1; i <= num2; i++) {
sum +=i;
}
System.out.print(sum);
}

Sum and Averages of an Array

I am working on an array problem for my college course and I'm trying to find the sum and the average of an array. Here's the code I have so far.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
//declare the array values
weeks[0]= 2;
weeks[1]= 4;
weeks[2]= 8;
weeks[3]= 10;
weeks[4]= 14;
weeks[5]= 16;
weeks[6]= 20;
weeks[7]= 22;
weeks[8]= 24;
weeks[9]= 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
I know that the average works but I'm stuck on the sum. The problem I'm having is I cant seem to initialize the values in the array so that I can provide a sum for them. What am I doing wrong or what am I missing?
You have two problems in your code;
A) For-loop assignment
You don't need to make the first assignment, just adding sum to the week[index] is ok;
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
B) Calculating the average
Sum is defined as an int which is a primitive integer, because of that, the division of an integer to an integer, the output is an integer which is not precise. Output of the division (45/10) is casted to integer, then assigned to double which is rounded off to 4, then casted to double again, and '4.0' became the result.
To avoid this unprecise result, cast sum to the double as below;
average = (double)sum / weeks.length;
The corrected version of your code is as below;
Demo
public class Module55 {
public static void main(String args[]) {
// declare the array to have 10 items for 10 weeks
// also declare sum as an int and average as a double to accommodate for
// decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
// declare the array values
weeks[0] = 2;
weeks[1] = 4;
weeks[2] = 8;
weeks[3] = 10;
weeks[4] = 14;
weeks[5] = 16;
weeks[6] = 20;
weeks[7] = 22;
weeks[8] = 24;
weeks[9] = 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Output
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
And a note for scope
And one last note about the scope, check out this code;
for (int index = 0; index < weeks.length; index++)
weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
In the for-loop, because that no brackets are used, only the first statement under the for-loop will be considered in the scope of the loop by the compiler. That's why, for the next line, the compiler is giving error about the index because index is defined inside the scope of the for-loop.
you need to use brackets in your for loop. currently your code is evaluating like this:
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index;
}
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
you want your code to evaluate like this
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index; //logical issue, what does this line achieve?
sum = sum + weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
This will at least solve your procedural problems but you will still need to take a look at your logic. Try using breakpoints to debug your code.
A very simple way to achieve this in Java 8 is to use the built in mechanisms for gathering statistics:
int[] weeks = {3, 4, 6, 9, 10};
IntSummaryStatistics stats = IntStream.of(weeks).summaryStatistics();
System.out.println("sum = " + stats.getSum() + "; average = " + stats.getAverage());
for (int i = 0;i < weeks.length) {
sum += weeks[i];
}
System.out.println("Sum is:" + sum);
First of all, you simply don't need the line weeks[index] = index;.
And for average you have to cast the sum to double if you want to get the average in double as you have declared the sum as int.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = {2,4,8,10,14,16,20,22,24,26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
//weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
Summing an array of numbers and dividing by n to get the average like this will not get the correct value - you should not compute the average using integer division.
Also, this approach might work for the example shown, but not in general. For example, try using this code to find the average of these two value: (INT_MAX-6) and (INT_MAX-2).
The corrected code. While calculating average you have cast on of the varibale to double else you will get the average as integer
public class Mod55 {
public static void main(String args[]) {
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) {
sum += weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0) {
average = (double)sum / weeks.length;
} else {
average = 0;
}
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Java8 You could achieve the same thing like this.
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = Arrays.stream(weeks)
.sum();
double average = Arrays.stream(weeks).average().orElse(0);
you can find this handy with lambdas.The code looks something like this.
int weeks[] = {1,2,3,4};
List<Integer> asd = IntStream.of(weeks).boxed().collect(Collectors.toList());
//asd.forEach(System.out::println);
//this outputs average
System.out.println(asd.stream().mapToDouble(val -> val).sum()/asd.size());
//this outputs sum
System.out.println(asd.stream().mapToInt(val -> val).sum());
//another way to achieve this thanks to commenter
System.out.println(IntStream.of(asd).summaryStatistics());

What is the average digit total of a given integer?

I have to use a static method TotalAverage(int n) that would calculate the average digit total of the numbers 0 + 1 + 2 + .... + n. So that totalAverage(19) would be calculated as (0 + 1 + ... + 9 + 1 + ... + 10) / 20.0. I managed to do it for the most part using the following code:
public static double TotalAverage(int n) {
double total = 0;
int count = 0;
while (n >= 0) {
total += n % 10;
n = n - 1;
count++;
}
return total / count;
}
It works for numbers up to 9, but I get incorrect results for larger numbers. I realise that once the while statements gets to 10 % 10 it adds 0 to the total and not a 10, but I can't figure out how to do it correctly.
If you're looking to sum all digits of a number then the error in your code is
total += n % 10;
which only get the ones digit from n. Use some loop to get all digits from n without modifying it (because if you modify n your outer loop will break). Try:
int temp = n;
while(temp>0) {
total += temp % 10; //add next digit
temp /= 10;
}
You could use a separate method for digit sum. Something like this would work.
private static int digitSum(int a) {
return a < 10 ? a : a%10 + digitSum(a/10);
}
Then you can replace the line
total += n % 10
with
total += digitSum(n);

Optimal algorithm for happy numbers

Given number is n digits find 2n digits numbers
that, for example
given number is 3 then 6n numbers are from 100000 -999999
then find count of those numbers that for example
123213
1 + 2 + 3 = 2 + 1 + 3
6 = 6
I found and wrote a program for calculating little numbers, but I need the fastest algorithm to find those numbers. Ideas?
my program :
Scanner scan = new Scanner(System.in);
System.out.println("enter n ");
int say = scan.nextInt();
say *= 2;
int low = (int) Math.pow(10, say - 1);
int max = (int) Math.pow(10, say) - 1;
int counter = 0;
int first = 0;
int last = 0;
for (int i = low; i <= max; i++) {
int number = i;
first = 0;
last = 0;
for (int j = 0; j < say / 2; j++) {
int k = number % 10;
first += k;
number /= 10;
}
for (int j = 0; j < say / 2; j++) {
int k = number % 10;
last += k;
number /= 10;
}
if (first == last) {
// System.out.println(i);
counter++;
}
}
System.out.println(counter);
The numbers are called lucky tickets in Russian (a link to ru.wikipedia.org). Yet, I don't seem to find a good explanation in English besides these slides.
Basically, let us say we have 2n digits, and we want the sum of first n be equal to the sum of last n. We first count c(d,s): the number of sequences of d digits which have sum s. Here, 0 <= d <= n and 0 <= s <= 9n. This can be done by dynamic programming: c(0,0)=1, and for d > 0, c(d,s) = c(d-1,s-0) + c(d-1,s-1) + c(d-1,s-2) + ... + c(d-1,s-9) since we can take any sequence of d-1 digits and write another digit from 0 to 9.
Now, the total number of lucky tickets is the sum for different s of the numbers of lucky tickets where the sum of the first n digits is s and the sum of the last n digits is s. When s is fixed, this number is equal to c(n,s) * c(n,s): there are exactly c(n,s) ways to choose the first half, and equally many to choose the second one.
Thus the answer is sum[s=0..9n] c(n,s)^2.
There are other solutions as well involving advanced maths, but for a programmer's assignment, this would suffice. Once again, I can't find a proper source in English — sorry! Here are a few popular articles in Russian, for what it's worth.
Edit: If you in fact need to account for numbers 100000 to 999999, not 000000 to 999999, a patch would be to calculate sum[s=0..9n] (c'(n,s) * c(n,s)), where c'(n,s) is the same table but calculated with disabled addition of zero digit when adding the first digit.

Categories