Я новичок и не знаю, что не так с моей программой.Мои методы сканирования не работают, и цикл 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: ");
}
}
}
}
Попробуйте написать вопрос до точки, а не как эссе. –
Возможно, консоль возвращает «123 \ n» вместо «123» в программу, попробуйте другой метод синтаксического анализа. – Gala
Все, что вы читаете из stdin, будет считано только как строка, если только он не проанализирован сканером в соответствующий тип данных/объект. Поэтому вы не можете знать, что сканер читал, если он не разбирает его. –