2017-01-29 2 views
-3

Я новичок и не знаю, что не так с моей программой.Мои методы сканирования не работают, и цикл while не прерывается.

Что бы я хотел, чтобы программа сделала, чтобы пользователь мог ввести Integer, который находится под MAX (1 000 000 000), но выше 0. Я также поставил блок исключений, используя методы try и catch, пользователь не может ввести строку.

Блок исключений работает, но он также выводит операторы внутри блока if, чего я не хочу.

Это то, что консоль печатает:

Number of marbles to divide: 
*three* 
Please enter a number not a word 
Try again: 
Please enter a number under 1 000 000 000 and above 0 
Try again: 

Я только хочу, чтобы напечатать ... Please enter a number not a word Try again: после того, как пользователь вводит строку. Я имею в виду, что я хочу, чтобы цикл while while прерывался, если пользователь ввел строку.

Еще одна проблема, которую я не могу решить, заключается в том, что если пользователь вводит Integer, значение которого превышает MAX (1 000 000 000), программа продолжается. Это то, что печатает консоль.

Number of marbles to divide: 
1000000001 
Number of people: 

Как вы можете увидеть программу продолжается, даже если пользователь ввел Integer над MAX (1 000 000 000)

Это мой код:

import java.util.*; 

public class MarblesApp 
{ 
    final static int MAX = 1000000000; 
    static int numberOfMarbles; 
    static int numberOfPeople, marblesPerPerson, marblesLeftOver; 
    static Scanner input = new Scanner(System.in); 
    public static void main(String[] args) 
    { 
     System.out.println("Welcome to the marble divvy-upper."); 
     System.out.println("This program will tell you how many marbles to give to each person.\n" 
    + "The maximum amount of marbles is 1 000 000 000. The maximum amount of people is the same.\n"); 

     System.out.println("Number of marbles to divide: "); 
      numberOfMarbles = GetMarbles(); 

     System.out.println("Number of people: "); 
      numberOfPeople = GetPeople(); 

     marblesPerPerson = (int)numberOfMarbles/numberOfPeople; 
     marblesLeftOver = (int)numberOfMarbles % numberOfPeople; 

     System.out.println("Give each child " + marblesPerPerson + " marbles."); 
     System.out.println("You will have " + marblesLeftOver + " marbles left over."); 
    } 
private static int GetPeople() 
{ 
    while (true) 
    { 
     try 
     { 
      return input.nextInt(); 
     } 
     catch(InputMismatchException f) 
     { 
      input.next(); 
      System.out.println("Please enter a number not a word\nTry again: "); 
     } 

     if(numberOfPeople > MAX || numberOfPeople == 0); 
     { 
      System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: "); 
     } 
    } 
} 
public static int GetMarbles() 
{ 
    while (true) 
    { 
     try 
     { 
      return input.nextInt(); 
     } 
     catch (InputMismatchException e) 
     { 
      input.next(); 
      System.out.println("Please enter a number not a word\nTry again: "); 
     } 

     if(numberOfMarbles > MAX || numberOfMarbles == 0); 
     { 
      System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: "); 
     } 

     } 
    } 
} 
+0

Попробуйте написать вопрос до точки, а не как эссе. –

+0

Возможно, консоль возвращает «123 \ n» вместо «123» в программу, попробуйте другой метод синтаксического анализа. – Gala

+0

Все, что вы читаете из stdin, будет считано только как строка, если только он не проанализирован сканером в соответствующий тип данных/объект. Поэтому вы не можете знать, что сканер читал, если он не разбирает его. –

ответ

2

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

Мне пришлось немного перестроить и сжать код. И я должен сделать некоторые замечания, относящиеся к более чистому коду:

  • метод-имен в Java всегда начинаются со строчной буквы, _ или $
  • избежать глобальных переменных, если вам не нужно их
  • избегать дублирования методов, которые отличаются от их имени

Надеюсь, этот код даст вам хорошее начало в JAVA. Повеселись!

import java.util.*; 

public class MarblesApp 
{ 
    private final static int MAX = 1000000000; 

    static Scanner input = new Scanner(System.in); 

    public static void main(String[] args) 
    { 
     int numberOfMarbles, numberOfPeople, marblesPerPerson, marblesLeftOver; 

     System.out.println("Welcome to the marble divvy-upper."); 
     System.out.println("This program will tell you how many marbles to give to each person.\n" 
    + "The maximum amount of marbles is 1 000 000 000. The maximum amount of people is the same.\n"); 

     System.out.println("Number of marbles to divide: "); 
      numberOfMarbles = getNumberFromConsole(); 

     System.out.println("Number of people: "); 
      numberOfPeople = getNumberFromConsole(); 

     marblesPerPerson = (int)numberOfMarbles/numberOfPeople; 
     marblesLeftOver = (int)numberOfMarbles % numberOfPeople; 

     System.out.println("Give each child " + marblesPerPerson + " marbles."); 
     System.out.println("You will have " + marblesLeftOver + " marbles left over."); 
    } 

    public static int getNumberFromConsole() 
    { 
     int number; 

     while (true) 
     { 
      try 
      { 
       // get the number from console 
       number = input.nextInt(); 

       // validate whether it's greater zero and lower MAX 
       if(validateNumber(number) == true) 
       { 
        // if true, return the number 
        return number; 
       } 
       else 
       { 
        // if not, input again 
        input.next(); 
       } 
      } 
      catch (InputMismatchException e) 
      { 
       System.out.println("Please enter a number not a word\nTry again: "); 
       input.next(); 
      } 
     } 
    } 

    private static boolean validateNumber(int number) { 

     if(number > MAX || number == 0) 
     { 
      System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: "); 
      return false; 
     } 

     return true; 
    } 
} 
+0

Большое спасибо. Я благодарю вас за беспокойство –