2016-04-09 201 views
2

我是编程新手,而且这个问题总是面临着我 当我运行程序时,Java忽略了一个字符串输入if if 我做错了什么?Java忽略字符串

import java.util.Scanner; 

public class JavaApplication { 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     System.out.print("------ FEEDBACK/COMPLAINT ------\n" 
       + "-------------------------------------\n" 
       + "| 1: Submit Feedback |\n" 
       + "| 2: Submit Complaint |\n" 
       + "| 3: Previous Menu |\n" 
       + "-----------------------------------\n" 
       + "> Please enter the choice: "); 
     int feedorcomw = input.nextInt(); 

     if (feedorcomw == 1) { 
      String name; 
      System.out.print("> Enter your name (first and last): "); 
      name = input.nextLine(); 
      System.out.println(""); 
      System.out.print("> Enter your mobile (##-###-####): "); 
      int num = input.nextInt(); 

     } 

    } 
} 
+0

你得到什么类型的错误? – Andrew

+2

也许这会解决你的问题http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods – RubioRic

+0

@和你的编辑没有太大意义 - 为什么把一个最小的完整例子变成一个不是仅仅修改格式的例子? – Flexo

回答

1

你ommitting的事实,扫描仪#nextInt方法不会消耗你输入的最后一个换行符,因此该换行符在下次调用消耗扫描仪#nextLine

尝试添加后,一个input.nextLine();,一切都将正常工作

例子:

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    System.out.print("------ FEEDBACK/COMPLAINT ------\n" 
      + "-------------------------------------\n" 
      + "| 1: Submit Feedback |\n" 
      + "| 2: Submit Complaint |\n" 
      + "| 3: Previous Menu |\n" 
      + "-----------------------------------\n" 
      + "> Please enter the choice: "); 
    int feedorcomw = input.nextInt(); 

    input.nextLine(); 
    if (feedorcomw == 1) { 
     String name; 
     System.out.print("> Enter your name (first and last): "); 
     name = input.nextLine(); 
     System.out.println(""); 
     System.out.print("> Enter your mobile (##-###-####): "); 
     int num = input.nextInt(); 

    } 

}