[英]Simple Java Exception Question
嘿,這只是課堂上的一個簡單的練習,我決定去做一個例外。根據書的輸入,這個問題應該采用以下格式:2009年4月19日我想要的是什么做我的例外是確保用戶(無論誰評級)遵循這些參數,以便我的程序工作。 這看起來不錯嗎? 我可以做得更好嗎?
編輯:感謝您的及時答復! 我知道我有很多東西需要學習,但希望有一天我能夠回答這里的問題。 干杯
import jpb.*;
public class ConvertDate {
public static void main(String[] args) {
try{
SimpleIO.prompt("Enter date to be converted: ");
String bam = SimpleIO.readLine();
bam = bam.trim().toLowerCase();
//empty space is taken off both ends and the entirety is put in lower case
int index1 = bam.indexOf(" ");
int index2 = bam.lastIndexOf(" ");
int index3 = bam.indexOf(",");
/*critical points in the original string are located using indexing to divide and conquer
in the next step*/
String month = bam.substring(0,index1);
String up = month.substring(0, 1).toUpperCase();
String rest = month.substring(1,index1);
String day = bam.substring(index1, index3).trim();
String year = bam.substring(index2+1);
//now all the pieces are labeled and in their correct cases
System.out.println("Converted date: " +day +" " +up +rest +" " +year);
//everything comes together so perfectly
} catch(StringIndexOutOfBoundsException e){
System.out.println("best type that in like the book does on page 125...");}
}
}
這里有一些想法。 這些只是我的意見,所以如果你願意,可以帶上一粒鹽或完全忽略:
import
語句在做什么,但是可以在不引入庫依賴的情況下完成所有這些操作。 您應該了解依賴關系的影響。 以下是我可能會寫同樣的事情:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class ConvertDate
{
private static final DateFormat DEFAULT_FORMAT;
static
{
DEFAULT_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
DEFAULT_FORMAT.setLenient(false);
}
public static void main(String[] args)
{
for (String dateString : args)
{
try
{
Date date = DEFAULT_FORMAT.parse(dateString);
System.out.println(date);
}
catch (ParseException e)
{
System.out.println("invalid date string: " + dateString);
}
}
}
}
通常使用異常作為程序邏輯的一部分是不受歡迎的。 你的邏輯應該是:
if(The Input is well formed){
parse the date
}else{
Tell the user that the input is wrong
}
但你的計划是:
try{
parse the date
}catch(){
tell the user the input is wrong
}
要確定輸入是否格式良好,您可以測試它的長度,獲取月份子串,並測試長度,獲取日子串並測試它是否為整數等。
程序永遠不應拋出StringIndexOutOfBoundsException,因為在使用substring方法之前,您可以檢查這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.