In this Program i am going to display sum of 1 to n numbers in Java.
Error Message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Duplicate local variable i
at com.lib.SumOf1ton.main(SumOf1ton.java:13)
Error Description:
In below program input is stored in variable i and in for loop index variable is also i,so i got an error.
package com.lib;
import java.util.Scanner;
public class SumOf1ton
{
public static void main(String[] args)
{
int Sum = 0,m;
Scanner rv = new Scanner(System.in);
System.out.println("enter value of m:");
int i = rv.nextInt();
for(int i=1;i<=m;i++)
{
Sum += i;
}
System.out.println(Sum);
}
}
Error Solution:
package com.lib;
import java.util.Scanner;
public class SumOf1ton
{
public static void main(String[] args)
{
int Sum = 0;
Scanner rv = new Scanner(System.in);
System.out.println("enter value of m:");
int m = rv.nextInt();
for(int i=1;i<=m;i++)
{
Sum += i;
}
System.out.println(Sum);
}
}
Output:
enter value of m:
4
10
Post a comment
Please share your valuable feedback and share this article in social media.