字符串不从扫描器类获取输入

时间:2015-02-20 07:56:48

标签: java

在while循环结束时,我使用scanner类将一个字符串作为用户的输入,但它没有接受任何输入。

我已经导入了Scanner类,但无法弄清楚为什么它不等待接受任何输入。

请指导我。

 import java.util.Scanner;

/**
*
* @author Student
*/
public class Exception {


public static void main(String[] args) {
   Scanner s = new Scanner(System.in);


   /*

            Creating a UserDefined Operations `   

   */


   while(1==1){

        System.out.println("\nEnter one of the following operations: ");
        System.out.println("1. Arithmeric Exception");
        System.out.println("2. ArrayIndexOutOfBounds Exception");
        System.out.println("3. NumberFormat Exception");
        System.out.println("4. Exit");

        int choice=s.nextInt();

        switch(choice)
        {
            case 1: 

                 //ArithmeticException 
                System.out.println("Enter the numerator: ");
                int num=s.nextInt();
                System.out.println("Enter the denomerator: ");
                try{
                    int dem=s.nextInt();
                    int divide=num/dem;
                }
                catch(ArithmeticException e){e.printStackTrace();}
                break;

            case 2:
                 //ArrayIndexOutOfBoundException 
                 System.out.println("Enter the size of array");
                 int size=s.nextInt();
                 int[] array = new int[size];
                 System.out.println("Enter the elements: ");
                 for(int x:array)
                     x=s.nextInt();
                 System.out.println("Enter the index of array to be accessed:");
                 try{
                      int index=s.nextInt();
                      System.out.println("The array to be accessed is: "+array[index]);
                 }catch(ArrayIndexOutOfBoundsException e){e.printStackTrace();}
                 break;


            case 3:
                     //NumberFormatException
                     System.out.println("Enter a number");
                     String s1=s.nextLine();
                     try{
                         Integer.parseInt(s1);
                     }
                     catch(NumberFormatException e){e.printStackTrace();}
                     break;
            case 4:
                    System.exit(0);
            default:
                    System.out.println("Invalid choice");

        }

        System.out.println("Do you want to continue:\nyes/no ");
        String str;
                str=s.nextLine();
        if(str.equals("no")||str.equals("No")||str.equals("n"))
            break;
        else
        {
            System.out.println("Invalid Input . Existing The Program");
            break;
        }

   }


   }
  }

2 个答案:

答案 0 :(得分:0)

因为你正在使用nextInt()所以它不会消​​耗换行符,所以稍后当你执行nextLine时,它将使用该空行。

所以你的问题的解决方案是在你的最后一个nextInt()

之后放下nextLine()

答案 1 :(得分:0)

s.nextInt()

之后添加以下行
s.nextLine();
相关问题