In: Computer Science
Write a java program that asks user to enter a set of positive integer values. When the user stops (think of sentinel value to stop), the program display the maximum value entered by the user. Your program should recognize if no value is entered without using counter.
If you have any queries please comment in the comments section I will surely help you out and if you found this solution to be helpful kindly upvote.
Solution :
Code:
import java.util.Scanner;
public class Hello
{
// main function
public static void main(String []args)
{
// make an object of Scanner class
Scanner sc = new Scanner(System.in);
// declare a string
String ele;
// initialize maximum element as 0
int max=0;
// run an infinite loop until a negative number is entered
while(true)
{
// input a string
ele = sc.nextLine();
// if the length of the string is 0 then no element is
entered
if (ele.length()==0)
{
System.out.println("No element entered...enter again");
}
// otherwise typecast the input string to integer
else
{
int val = Integer.parseInt(ele);
// if the value is negative then break
if(val<0)
{
break;
}
else
{
// otherwise check if the value id greater than
max
if(val>max)
{
// if it is greater then make max = val
max=val;
}
}
}
}
// print the maximum element
System.out.println("Maximum element is "+max);
}
}
Output :