简体   繁体   English

Java:使用扫描仪退出 try-catch 块时,Int 变量始终恢复为旧值

[英]Java : Int variable always reverts to old value when exiting try-catch block with scanner

I'm absolutely stumped here and after many hours of fiddling I just can't seem to get it to work:我在这里完全被难住了,经过几个小时的摆弄,我似乎无法让它工作:

The function below is basically a menu.下面的function基本上就是一个菜单。 It will ask you to input either 1, 2 or 3 and return that int.它将要求您输入 1、2 或 3 并返回该 int。

If you input anything other than an int, it'll catch it and launch the menu again.如果您输入除 int 以外的任何内容,它会捕获并再次启动菜单。 If you input an int other than 1-2-3 it will tell you, and launch the menu again.如果您输入 1-2-3 以外的 int,它会告诉您,然后再次启动菜单。

The problem is that if you make an invalid input, it tells you the right thing, relaunches the menu, but then if you make a CORRECT input, it will return the invalid value you tried before instead of the new, good one.问题是,如果您输入无效,它会告诉您正确的事情,重新启动菜单,但是如果您输入正确的输入,它将返回您之前尝试过的无效值,而不是新的、好的值。

I followed it line-by-line and it will hit the return from my if, and then hit the return at the end of the try-catch and "choixDeMenu" reverts to the old invalid value and it returns that.我逐行跟踪它,它会从我的 if 中返回,然后在 try-catch 的末尾返回返回,“choixDeMenu”恢复为旧的无效值并返回该值。 If you were notified that it wasn't an int, it returns 0, but if it was an invalid int, it will return that invalid int.如果你被告知它不是一个 int,它返回 0,但如果它是一个无效的 int,它会返回那个无效的 int。

If you make a VALID input right away, the function works and returns your valid input.如果您立即进行 VALID 输入,function 将工作并返回您的有效输入。 It's only when you try invalid things first that I get problems.只有当您首先尝试无效的事情时,我才会遇到问题。

public static int menu()
{
  int choixDeMenu = 0;
  System.out.println ("Sélectionner le fichier à importer :");
  System.out.println ("1. Partie 1.");
  System.out.println ("2. Partie 2.");
  System.out.println ("3. Partie 3.");
  
  Scanner waitingForChoice = new Scanner(System.in);

  try
    {
      choixDeMenu = waitingForChoice.nextInt();
      if (choixDeMenu < 4 && choixDeMenu > 0)
      {
        waitingForChoice.close();
        return choixDeMenu;
      }
        else
        {
          System.out.println("Entrée invalide. Entrer 1, 2, ou 3.");
          menu();
        }  
    } 
      catch (InputMismatchException e)
      {
        System.out.println("Doit être un chiffre. Entrer 1, 2, ou 3.");
        menu();
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
      
  return choixDeMenu;
}

Any time you create a menu like this, you should contain it within a while loop.任何时候创建这样的菜单时,都应该将它包含在一个 while 循环中。 So, rather than calling a new method ( menu() ) each time the user is prompted to make a choice, you are simply circling back to the beginning of the block and repeating the same actions ( System.out.println("1..) ).因此,不是每次提示用户做出选择时都调用一个新方法( menu() ),而是简单地循环回到块的开头并重复相同的操作( System.out.println("1..) )。

If you're required to do this using only try/catch, this can still take place within a while loop.如果您只需要使用 try/catch 来执行此操作,这仍然可以在 while 循环内进行。

From there you can use either a switch statement or a group if-else to validate each possible choice and return the value.从那里您可以使用 switch 语句或组 if-else 来验证每个可能的选择并返回值。 If you're required to use a try/catch, you can contain the switch or if-else within that.如果您需要使用 try/catch,您可以在其中包含 switch 或 if-else。

With the help of the commenters, here is how I modified it so it works:在评论者的帮助下,这是我对其进行修改的方式:

Dumped everything in a while loop, and since the validity of the choice depends on either the right type of input OR an input of the right type in the proper range, I added a boolean to take note of that and operate the while loop using it.在while循环中转储所有内容,并且由于选择的有效性取决于正确的输入类型或正确范围内的正确类型的输入,我添加了一个 boolean 来记录这一点并使用它来操作while循环.

Thanks for everything.感谢一切。

public static int menu()
{
  int choixDeMenu = 0;
  boolean validChoice = false;
  while (validChoice == false)
  {
    System.out.println ("Sélectionner le fichier à importer :");
    System.out.println ("1. Partie 1.");
    System.out.println ("2. Partie 2.");
    System.out.println ("3. Partie 3.");
    Scanner waitingForChoice = new Scanner(System.in);
    
    try
    {      
      choixDeMenu = waitingForChoice.nextInt();
      if (choixDeMenu < 4 && choixDeMenu > 0)
      {
        waitingForChoice.close();
        validChoice = true;
        return choixDeMenu;
      }
        else
        {
          validChoice = false;
          System.out.println("Entrée invalide. Entrer 1, 2, ou 3.");
        }  
    } 
      catch (InputMismatchException e)
      {
        validChoice = false;
        System.out.println("Doit être un chiffre. Entrer 1, 2, ou 3.");
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
  } 
  return choixDeMenu;
}

Try this code hope this help试试这个代码希望这有帮助

    public static int menu()
{
  int choixDeMenu = 0;
  System.out.println ("Sélectionner le fichier à importer :");
  System.out.println ("1. Partie 1.");
  System.out.println ("2. Partie 2.");
  System.out.println ("3. Partie 3.");

  Scanner sc = new Scanner(System.in);

  int prev=0;
  int flg=0;

  while(true){
    try{
    choixDeMenu = sc.nextInt();
    if(choixDeMenu>0 && choixDeMenu<4){
      if(flg==0){
        return choixDeMenu;
      }
      else{
        return prev;
      }
    }
    else{
      System.out.println("Entrée invalide. Entrer 1, 2, ou 3.");
      prev = choixDeMenu;
      flg=1;
      continue;
    }
  }
  catch(InputMismatchException e)
      {
        System.out.println("Doit être un chiffre. Entrer 1, 2, ou 3.");
        sc.next();
        continue;
      }
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM