Home > Back-end >  How to Finds The Smallest Number In Loop Scanner
How to Finds The Smallest Number In Loop Scanner

Time:11-22

Dears,

I need to find the Lowest number in the loop scanner. 0 to stop the program. The issue I phased is that every time the lowest will be 0. What is wrong with this code?

import java.util.Scanner;
public class Loop_Scanner {
    public static void main(String[] args) {
        int x=1;
        int largest = 0;
        int Lowest = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number: ");
        if(x>0) {
            while (x != 0) {
                x = input.nextInt();
                if (largest<=x){
                    largest=x;
                } else if (Lowest >=x ) {
                    Lowest =x;
                }
            }
            System.out.println("The Largest Number is: " largest);
            System.out.println("The Smallest Number is: " Lowest);

        }
        else {
            System.out.println("Wrong Value");
        }
}}

CodePudding user response:

on your code

else if (Lowest >=x ) {
            Lowest =x;
      }

Lowest value is always 0 because the lowest value is set to 0

set the first value to the lowest value

CodePudding user response:

This is the solution for my problem. Thank you all.

import java.util.Scanner;
public class Loop_Scanner {
    public static void main(String[] args) {
        int x=1;
        int largest = 0;
        int Lowest = Integer.MAX_VALUE;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number: ");
        while (x != 0) {
            x = input.nextInt();
            if (x > 0) {

                if (largest <= x) {
                    largest = x;
                } else if (Lowest >= x) {
                    Lowest = x;
                } else if(x<0) {
                    System.out.println("Wrong Value");
                }
            }
        }
            System.out.println("The Largest Number is: "   largest);
            System.out.println("The Lowest Number is: "   Lowest);
    }
}

CodePudding user response:

public class Loop_Scanner {
    public static void main(String[] args) {
        int x = 1;
        int largest = 0;
        int lowest = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number: ");
        while (x != 0) {
            x = input.nextInt();
            if (x < 0) {
                System.out.println("Wrong Value");
                continue;
            }
            if (largest <= x){
                largest = x;
            }
            if (lowest >= x ) {
                lowest = x;
            }
        }
        System.out.println("The Largest Number is: "   largest);
        System.out.println("The Smallest Number is: "   lowest);
    }
}
  •  Tags:  
  • java
  • Related