2013-10-03 4 views
2

Этот код в порядке и хорошо работает.Сканирование не останавливается на hasNextInt()

public static void main(String[] args) { 
    String [] keywords={"auto","break","case","char","const","continue","default", 
      "do","double","else","enum","extern","float","for","goto","if","int", 
      "long","register","return","short","signed","sizeof","static","struct", 
      "switch","typedef","union","unsigned","void","volatile","while" }; 
    Scanner sn = new Scanner (System.in); 
    if(Arrays.asList(keywords).contains(sn.next())) { 
      System.out.println("This is a KEYWORD"); 
     } 

Но когда я добавить

else if(sn.hasNextInt()){ 
     System.out.println("This is an INTEGER"); 
    } 

и беги, мой вход сканера не останавливается, а для этого, я не получаю никакого результата. Почему это происходит?

Пожалуйста, дайте мне решение с описанием. Заранее спасибо.

+0

Что вы подразумеваете под «не останавливаться»? –

+0

не останавливается, это не дает мне выход и все еще сканирует вход. –

ответ

1
import java.util.Arrays; 
import java.util.Scanner; 


public class jh { 

    public static void main(String[] args) { 
     String [] keywords={"auto","break","case","char","const","continue","default", 
       "do","double","else","enum","extern","float","for","goto","if","int", 
       "long","register","return","short","signed","sizeof","static","struct", 
       "switch","typedef","union","unsigned","void","volatile","while" }; 
     Scanner sn = new Scanner (System.in); 
     /* get the value from scanner.. do not scan a single input twice. 
     In your code in line Arrays.asList(keywords).contains(sn.next())) {, you have 
     already got the input once. If you had tried entering another integer after that and you 
     should have got the This is an INTEGER 
     */ 
     String string = sn.next(); 
     Integer someInt = null; 
     try{//see if the input was an integer 
     someInt= Integer.parseInt(string); 
     }catch(NumberFormatException e){System.out.println(e);} 

     if(Arrays.asList(keywords).contains(string)) { 
       System.out.println("This is a KEYWORD"); 
      } 
     else if(someInt!=null){ 
      System.out.println("This is an INTEGER"); 
     } 

} 
} 
+0

Это нормально, но когда я добавляю тот же код с этим кодом для Double value, он не работает. –

+0

Что вы пробовали? добавьте свой код в качестве обновления –

0

Я не согласен с Mr.Vihar1903 ... bcoz этой проблемы не из-за только hasNext() ... это bcoz первый вход всегда идти к этой линии если (Arrays.asList (ключевые слова) .contains (sn.next())) { , а затем следующий вход приходит к следующему ..... лучше сохранить свой первый вход в консоль в строковой переменной, например String str = sc.next(); После этого вы можете сравнить его ............

0
/** 
* 
* @author hjayamanna001 
*/ 
import java.io.*; 
import java.util.Arrays; 
import java.util.Scanner; 

public class JavaApplication1 { 

    public static void main(String[] args) throws IOException { 

     String[] keywords = {"auto", "break", "case", "char", "const", "continue", "default", 
      "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", 
      "long", "register", "return", "short", "signed", "sizeof", "static", "struct", 
      "switch", "typedef", "union", "unsigned", "void", "volatile", "while"}; 
     String s = ""; 
     int i = 0; 
     while (true) { 
      System.out.println("--------------------"); 
      System.out.println("Input a character: "); 
      Scanner sn = new Scanner(System.in); 
      s = sn.next(); 
      try { 
       if (Arrays.asList(keywords).contains(s)) { 
        System.out.println("This is a KEYWORD"); 

       } else { 
        i = Integer.parseInt(s); 
        System.out.println("This is an INTEGER"); 
       } 
      } catch (Exception e) { 
       System.out.println("This is not MATCHING"); 
      } 
     } 
    } 
} 
Смежные вопросы