Home > Back-end >  When the value of input = 0 or negative in Java
When the value of input = 0 or negative in Java

Time:11-12

If strangers count is zero, then program must print "Oh, it looks like there is no one here". If strangers count is negative, then program must print "Seriously? Why so negative?"

Scanner sc = new Scanner(System.in);
    System.out.print("Number: ");
    String[] string = new String [sc.nextInt()];
    sc.nextLine();

    for (int i = 0; i < string.length; i  )
    {
    string[i] = sc.nextLine(); 
    }
    System.out.println("\nYou have entered:");
    for(String str: string)
    {
    
    System.out.println("Hello : "   str);
    }

How can i add this 2 statements ??

CodePudding user response:

I would check the number from user input before initializing the array to avoid running into exceptions when a negative number is entered.

    Scanner sc = new Scanner(System.in);
    System.out.println("Number: ");
    int strangers = sc.nextInt();
    if (strangers == 0) {
        System.out.println("Oh, it looks like there is no one here");
    } else if (strangers < 1) {
        System.out.println("Seriously? Why so negative?");
    } else {
        String[] string = new String[sc.nextInt()];
        sc.nextLine();

        for (int i = 0; i < string.length; i  ) {
            string[i] = sc.nextLine();
        }
        System.out.println("\nYou have entered:");
        for (String str : string) {

            System.out.println("Hello : "   str);
        }
    }

CodePudding user response:

I think you are looking for this kind of example.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Number: ");
    try{
        String[] string = new String [sc.nextInt()];
        sc.nextLine();

        for (int i = 0; i < string.length; i  )
        {
            string[i] = sc.nextLine();
        }
        System.out.println("\nYou have entered:");

        if(string.length == 0){
            System.out.println("Oh, it looks like there is no one here");
        }else{
            for(String str: string)
            {
                System.out.println("Hello : "   str);
            }
        }
    }catch (java.lang.NegativeArraySizeException e){
        System.out.println("Seriously? Why so negative?");
    }


}
  •  Tags:  
  • java
  • Related