-1

I want user to enter the number of rows for the following pattern, so please mark my mistake.As I am beginner in java so please suggest me some book also. This pattern must be shown

**********   
*********    
********     
*******      
******       
*****        
****         
***          
**           
* 

And this is a code:

import java.util.Scanner;
class pattern{
public static void main (String agrs[]){

int n;
Scanner in =new Scanner(System.in);
System.out.println("enter the no. of rows in the pattern");
n= in.nextInt();
{
for(int i=0;i<n;i++)
{   for(int j=0; j<=i;j++)

System.out.print(" * ");
System.out.println(" ");
}}
}}

  ERROR   ...... 
 enter the no. of rows in the pattern
 Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at pattern.main(pattern.java:8)
herry
  • 1,708
  • 3
  • 17
  • 30
ashish
  • 15
  • 4

2 Answers2

4

If you check the documentation on the oracle site, the expanation for the Exception is:

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

This Exception is thrown when non integer input is entered.

You need to add a try/catch to catch this, and inform the user of wrong input.

Example:

import java.util.Scanner;

public class PatternTest {
    public static void main(String agrs[]) {

        int n = -1;     

        do
        {
            try {
                Scanner in = new Scanner(System.in);    
                System.out.println("enter the no. of rows in the pattern");
                n = in.nextInt();               
            } catch (java.util.InputMismatchException e) {
                System.err.print("Please enter only an integer.");
            }
        }while(n == -1);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++)
            System.out.print(" * ");
            System.out.println(" ");
        }

    }
}

Update

int n = -1;     

do
{
    try {
        Scanner in = new Scanner(System.in);    
        System.out.println("enter the no. of rows in the pattern");
        n = in.nextInt();               
    } catch (java.util.InputMismatchException e) {
        System.err.print("Please enter only an integer.");
    }
}while(n == -1);

for (int rowNumber = n; rowNumber > 0; rowNumber--) {

    for (int columnNumber = 0; columnNumber < rowNumber; columnNumber++)
    System.out.print("*");  

    System.out.println(" ");
}
Menelaos
  • 23,508
  • 18
  • 90
  • 155
0

Try to see the documentation.It's clear here Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is thrown.

See also.

Community
  • 1
  • 1