سؤال
أحاول أن أحلق استثناءً ، لكن لسبب ما لا يعطيني خيار إعادة كتابة ملف الماسح الضوئي الخاص بي:
لا أعرف كيفية استخدام BufferedReader ، ولهذا السبب أستخدم هذا. أي أدلة؟
هذا هو صفي القياسي مع طريقتي
package arrayExceptionsWithInput;
import java.util.*;
public class GetThoseNumbersBaby {
int firstInt;
int secondInt;
boolean error;
Scanner yourNumbers = new Scanner(System.in);
public void findNumbers()
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
}
}
وهنا فصلي الرئيسي باستثناء استثناء مع حلقة:
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
GetThoseNumbersBaby zack = new GetThoseNumbersBaby();
{
do {
try
{
zack.findNumbers();
}
catch(InputMismatchException Q)
{
System.out.println(" one of your integers was incorrect, please try again");
Q.printStackTrace();
error = true;
}
} while (error == true);
}
error = false;
}
}
إذا كان لدى أي شخص أي أفكار حول كيفية حلقة هذا بشكل مختلف ، فأنا كل آذان.
المحلول 2
قررت أن أتخلص أيضًا من فئة الطريقة وأضع الطريقة في منطقة الاستثناء المحاولة.
تستخدم. nextline بعد الماسح الضوئي ويبدو أنه ثابت.
هذا يبدو على ما يرام؟
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
int firstInt;
int secondInt;
Scanner yourNumbers = new Scanner(System.in);
{
do{
try
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
yourNumbers.nextLine();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
yourNumbers.nextLine();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
yourNumbers.nextLine();
}
catch(InputMismatchException Q)
{
Q.printStackTrace();
System.out.println(" one of your integers was incorrect, please try again");
error = true;
yourNumbers.nextLine();
}
}while (error == true);
}error = false;
}
}
نصائح أخرى
تعيين خطأ خطأ قبل الحدث. وبهذه الطريقة لديك شرط الخروج الصحيح إذا حصل المستخدم عليه بشكل صحيح.
error = false;
zack.findNumbers();
أنت حلقة أثناء 'خطأ' المتغير له قيمة 'حقيقي'. ومع ذلك ، يصبح 'حقيقي' فقط عندما يتم إلقاؤه (أي متى 'امساك' يتم تنفيذ الكتلة). تدفق التحكم لا يصل إليه.
لا تنتمي إلى StackOverflow