2016-10-13 4 views
1

Я пытаюсь взять ввод с консоли, но ничего не печатается. Я отлаживал код, и он правильно хранит значения в массиве, но ничего не печатается. Я новичок в java. Пожалуйста помоги.Код ничего не печатает

import java.util.Scanner; 

public class noofdays { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     int[] date = new int[10]; 
     int i = 0; 

     Scanner in = new Scanner(System.in); 

     while (in.hasNextInt()) { 
      date[i]=in.nextInt(); 
      i++; 
     } 

     for(i=0;i<3;i++) 
     { 
      System.out.println(date[i]); 
     } 
    } 
} 
+0

что 'while' цикл здесь делает? – emotionlessbananas

+0

Использовать отладчик, и вы будете отказываться от того, что случилось – Jens

+0

while loop для получения ввода с консоли @AsteriskNinja – user3797489

ответ

2

Я не нахожу ничего плохого с вашим кодом, он может просто вести себя немного иначе, чем вы ожидаете. Итак, вот как я это сделаю.

Одно первое: имена классов должны всегда начинаться с заглавной буквы (не ошибка, а скорее конвенции, которая помогает понять код)

public static void main(String[] args) throws IOException{ 
    int[] date = new int[10];  // as mentioned above, a fixed size array will limit you - but if 10 is what you want, then this is what you need 
    int i = 0; 

    System.out.println("Please enter " + date.length + " numbers"); // just some output to tell the user that the program has started and what to do next 
    Scanner in = new Scanner(System.in);  // perfect 
    // if you absolutely want your array filled, check if you reached the end of your input to avoid IndexOutOfBoundsExceptions. 
    // in.hasNext() will check for ANY input, which makes it easier to handle unwanted user input 
    while(i < date.length && in.hasNext()){ 
     if(in.hasNextInt()){  // here you check if the input starts with a number. Beware that "1 w 2" is valid too! 
      date[i] = in.nextInt(); 
      i++; 
     }else{ 
      // this is to advise the user of an input error 
      // but more importantly, in.next() will read the invalid input and remove it from the inputstream. Thus your scanner will continue to read the input until it ends 
      System.out.println("sorry \"" + in.next() + "\" is not a valid number"); 
     } 
    } 
    System.out.println("your input:"); 
    for(i = 0; i < date.length; i++){ // you don't need any advanced loops, it is perfectly fine to use indexed loops. Just try to make your break condition more dynamic (like checking the length of the array instead of a constant value) 
     System.out.println(date[i]); 
    } 
} 

Это ни решение, ни лучший способ сделай это. Я просто пытаюсь показать вам, как вы можете направлять пользователя и обрабатывать нежелательный вход.

редактировать: в двух словах, эти вещи должны быть рассмотрены:

  • не делают никаких предположений о разумности вашего пользователя, он/она может что-нибудь вход: 1 two 2.3 , 4 . @¹"
  • быть уверены, вам нужны номера 10, в противном случае используйте массив другого размера или список (если вы не знаете, сколько цифр вам нужно)
  • Возможно, пользователь не хочет вводить столько чисел и хочет выйти ранее (if(in.next().equalsIgnoreCase("q") мог трюк)
  • Вы принимаете целые числа? даже отрицательные?
  • Вы должны принять long или даже BigInteger?
  • Что относительно плавающих точек?
  • и как вы хотите обработать ошибку?игнорировать его, заменить его значением по умолчанию, выйти из цикла или даже программы?

И вот несколько примеров работает:

Please enter 10 numbers 
1 
2 
3 4 5 6 7 8 9 
10 
your input: 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

Please enter 10 numbers 
1 2 3 4 5 6 7 8 9 10 
your input: 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

Please enter 10 numbers 
1 2 3 4 r 5 6 7 8 9 10 
sorry "r" is not a valid number 
your input: 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

Please enter 10 numbers 
1 2 3 4 5 6 7 8 9 10 11 
your input: 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
-2

int [] date = new int [10]; int i = 0;

Scanner in = new Scanner(System.in); 

    while (in.hasNextInt()) { 

     date[i]=in.nextInt(); 
     System.out.println(date[i]); 
     i++; 

    } 
+2

не могли бы вы объяснить, как это решает проблему OPs? – GameDroids

1

, поскольку цикл не остановится:

while (in.hasNextInt()) { 
      date[i]=in.nextInt(); 
      i++; 
} 

поэтому код не может быть выполнена:

for(i=0;i<3;i++) 
     { 
      System.out.println(date[i]); 
} 

может быть, вы можете использовать это:

public static void main(String[] args){ 
      int[] date = new int[10]; 
      int i = 0; 
      Scanner in = new Scanner(System.in); 
      for(i=0;i<3;i++) { 
       date[i]=in.nextInt(); 
      } 

      for(i=0;i<3;i++) 
      { 
       System.out.println(date[i]); 
      } 
     } 
+0

Это правильный ответ, вы столкнулись с бесконечным циклом в 'while', и это кажется очевидным выбором для замены того, что вы пытаетесь сделать. – px06

+1

@ px06 в вопросе ОП нет бесконечной петли. – John

+0

@John кажется так, потому что сканер будет продолжать чтение ввода до тех пор, пока не достигнет некоторого «конечного» состояния, которое, похоже, не происходит в контексте. [Это объясняет это немного лучше] (http://stackoverflow.com/questions/10490344/how-to-get-out-of-while-loop-in-java-with-scanner-method-hasnext-as-condition). – px06

1

Вы нужно указать в своем цикле, где нужно прекратить ждать ввода , Если вы хотите ввести строку integers, вы можете просто использовать nextLine() и использовать вместо этого String.

Этот пример займет одну строку ввода и вывода допустимых значений.

public static void main(String[] args) { 

    // use a List, unless you want to enter exactly 10 integers 
    List<Integer> date = new ArrayList<Integer>(); 
    int i = 0; 
    String x = ""; 

    Scanner in = new Scanner(System.in); 
    x = in.nextLine(); 

    String [] tokens = x.split(" "); 


    for (int y = 0; y < tokens.length; y++) { 
     try { 
      date.add(Integer.parseInt(tokens[y])); 
     } catch (Exception e) { 
      // error handling 
      date.add(-1); // set a default value instead or just do nothing 
     } 
    } 

    in.close(); // don't forget to close your Scanner 

    for (i = 0; i < date.size(); i++) { 
     System.out.println(date.get(i)); 
    } 
} 

Вход:

1 2 3.5 foo 50 bar 1234 

Выход:

1 
2 
-1 
-1 
50 
-1 
1234 
+0

закрытие сканера - хороший момент! – GameDroids

Смежные вопросы