如何在 Java 中限制/约束用户输入



如果用户在控制台中键入三个以上的整数,我希望出现错误消息。因此,如果控制台显示"键入三个整数",而用户键入 123 244 242,则无论数字大小如何,它都应该正常运行。但是,如果用户键入 123 244 242 442,那么当他们按 run 时,我希望出现一条错误消息。但不完全确定如何做到这一点。

这是简单的程序:

import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    System.out.print("Type three integers ");
    int firstInt = userInput.nextInt();
    int secondInt = userInput.nextInt();
    int thirdInt = userInput.nextInt();
            System.out.println(firstInt + secondInt + thirdInt);
    }
}

谢谢

int firstInt = userInput.nextInt();
int secondInt = userInput.nextInt();
int thirdInt = userInput.nextInt();
char run = userInput.next().charAt(0);
if(userInput.hasNext())
{
   System.out.println("Error, you need 3 numbers only, and a char");
   userInput.nextLine(); //clears the rest of the line
}

一试,看看进展如何。我建议在 while 循环中将其设置为启动,以便它将继续为数字启动,直到它毫无错误地获得所有数字。

public static void main(String[] args)
{
   boolean getNumbers = true;
   int firstInt, secondInt, thirdInt;
   Scanner userInput = new Scanner(System.in);
   while(getNumbers)
   {
      firstInt = userInput.nextInt();
      secondInt = userInput.nextInt();
      thirdInt = userInput.nextInt();
      char run = userInput.next().charAt(0);
      if(userInput.hasNext())
      {
         System.out.println("Error message here");
         userInput.nextLine(); //clear the rest of line
         firstInt = secondInt = thirdInt = 0;
         run = '';
      }
      else
      {
         getNumbers = false;
      }
   }
   //do calculations with numbers here
}

相关内容

  • 没有找到相关文章

最新更新