90.3k views
12 votes
Write a program that asks the user for a positive integer value. The program should use a loop to get the sum of all even integers from 0 up to the number entered, and then display the sum. For example, if the user enters 11, the loop will find the sum of 2, 4, 6, 8, and 10. Input validation: Do not accept a negative number or 0 from user input

1 Answer

13 votes

import java.io.*;

public class GFG {

// Returns true if s is

// a number else false

static boolean isNumber(String s)

{

for (int i = 0; i < s.length(); i++)

if (Character.isDigit(s.charAt(i)) == false)

return false;

return true;

}

// Driver code

static public void main(String[] args)

{

// Saving the input in a string

String str = "6790";

// Function returns 1 if all elements

// are in range '0 - 9'

if (isNumber(str))

System.out.println("Integer");

// Function returns 0 if the

// input is not an integer

else

System.out.println("String");

}

}

User Tim Schmelter
by
5.0k points