简体   繁体   English

为什么我的异常不会打印出它的打印语句? (爪哇)

[英]Why will my exception not print out its print statement? (Java)

The print statement in my exception never prints out.我的异常中的打印语句永远不会打印出来。 If I do not enter anything it will just continue to ask me to enter name of cruise ship.如果我不输入任何内容,它只会继续要求我输入游轮名称。 I need it to throw the exception print statement along with that if someone were to enter an empty string or anything other than a string.如果有人要输入空字符串或字符串以外的任何内容,我需要它抛出异常打印语句。

 do {
  try {
      System.out.println("Enter name of cruise ship: ");
      cruiseShipName = scnr.nextLine();

      }
  catch(Exception e){
      e.printStackTrace();
        System.out.println("Invalid Input. Please try again.");
    }
} while (cruiseShipName.equals(""));

Maybe your code will not throw any exception if the scnr.nextLine() is empty.如果 scnr.nextLine() 为空,您的代码可能不会抛出任何异常。

In your case if you want to ask the user to try again, you could do as following:在您的情况下,如果您想要求用户再试一次,您可以执行以下操作:

` `

do {
    System.out.println("Enter name of cruise ship: ");
    cruiseShipName = scnr.nextLine();
    if (cruiseShipName.equals("")) {
        System.out.println("Invalid Input. Please try again.");
    }
} while (cruiseShipName.equals(""));

` `

The may help you.可能会帮助你。


do {
  try {
      System.out.println("Enter name of cruise ship: ");
      cruiseShipName = scnr.nextLine();
      if(cruiseShipName.equals("")) throw new Exception("");
      }
  catch(Exception e){
      e.printStackTrace();
        System.out.println("Invalid Input. Please try again.");
    }
} while (cruiseShipName.equals(""));


This code doesn't actually throw an exception.这段代码实际上并没有抛出异常。 You don't have anything that checks if the input is valid and throws an exception if it isn't.您没有任何东西可以检查输入是否有效,如果无效则抛出异常。

So right now, the input is always valid.所以现在,输入总是有效的。

The print statement in my exception never prints out.我的异常中的打印语句永远不会打印出来。 If I do not enter anything it will just continue to ask me to enter name of cruise ship.如果我不输入任何内容,它只会继续要求我输入游轮名称。 I need it to throw the exception print statement along with that if someone were to enter an empty string or anything other than a string.如果有人要输入空字符串或字符串以外的任何内容,我需要它抛出异常打印语句。

 do {
  try {
      System.out.println("Enter name of cruise ship: ");
      cruiseShipName = scnr.nextLine();

      }
  catch(Exception e){
      e.printStackTrace();
        System.out.println("Invalid Input. Please try again.");
    }
} while (cruiseShipName.equals(""));

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

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