亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

“異常:掃描儀已關閉”如何在(while..循環)內重新打開它

“異常:掃描儀已關閉”如何在(while..循環)內重新打開它

呼如林 2023-11-01 21:56:08
我是編碼新手,正在嘗試學習 JAVA,并使用不同的方法來完成簡單的任務。我想制作一個簡單的通訊錄,具有“添加聯系人、按號碼搜索、按姓名搜索等”功能。我的大多數方法都有效,但以下兩種方法有問題。當我調用時modify Contact,即使我嘗試替換名稱,代碼也會在文件中創建一個新行。然后我調用delete By Name刪除未修改的行,并且收到以下錯誤。(我知道錯誤的原因,但我找不到有效的解決方案......)  public static void modifyContact(String namee){        Scanner sca =new Scanner(System.in);        String newName = sca.nextLine();        try  {            String[] s;            boolean foundPerson = false;            Scanner sc = new Scanner(new File("addressBook.txt"));            while (sc.hasNextLine()) {                s = sc.nextLine().split(",");                if (s[0].equals(namee)) {                    s[0]=s[0].replace(s[0],newName);                    System.out.println("Name is " + namee + " phone number is " + s[1] + " ,address is " + s[3] + " and email is " + s[2]);                    foundPerson = true;                    deleteByName(namee);                File file =new File("addressBook.txt");                FileWriter pw = new FileWriter(file,true);                pw.write(s[0]+","+s[1]+","+s[2]+","+s[3]);                pw.close();                }            }            sc.close();            deleteByName(namee);            if (!foundPerson) {                System.out.println("No contact found with " + namee);                }            }             catch (IOException ex) {           //System.out.println(ex.getMessage());                }    }    public static void deleteByName(String na){        try{            File inputFile = new File("addressBook.txt");   // Your file            File tempFile = new File("TempFile.txt");// temp file        BufferedReader reader = new BufferedReader(new FileReader(inputFile));        BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));        String currentLine;        while((currentLine = reader.readLine()) != null) {            if(currentLine.contains(na))                   continue;            writer.write(currentLine);            writer.newLine();        }
查看完整描述

5 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

有兩種解決方案:

  • 不要關閉掃描儀。保持其打開狀態,直到不需要為止。換句話說,在循環之后關閉它。

  • 通過調用 重新創建掃描儀sc = new Scanner(new File("addressBook.txt"));。但是,由于這將創建一個新的掃描儀,因此它將再次從第一行開始讀取。


查看完整回答
反對 回復 2023-11-01
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

sc.close();您應該在 while 循環之后調用,而不是在其中調用。按照您的邏輯,掃描儀從循環本身的第二次迭代開始就無法使用。



查看完整回答
反對 回復 2023-11-01
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

您的主要問題是您deleteByName()在循環內調用刪除原始文件然后重用Scanner.

你應該這樣做:

  1. 找到所有name

  2. 呼叫deleteByName()與所有發現names。

public final class AddressBookManager {


    private final File file;


    public AddressBookManager(File file) {

        this.file = file;

    }


    public void modifyContact(String oldName, String newName) throws IOException {

        if (isContactExists(oldName))

            updateContactName(oldName, newName);

    }


    private boolean isContactExists(String name) throws FileNotFoundException {

        try (Scanner scan = new Scanner(file)) {

            while (scan.hasNextLine()) {

                String str = scan.nextLine();


                if (str.startsWith(name + ',')) {

                    String[] parts = str.split(",");

                    System.out.format("Contact found. Name '%s', phone number '%s', address '%s', email '%s'\n", parts[0], parts[1], parts[2],

                            parts[3]);

                    return true;

                }

            }


            System.out.println("No contact found with name '" + name + '\'');

            return false;

        }

    }


    private void updateContactName(String curName, String newName) throws IOException {

        File tmp = new File(file.getParent(), "TempFile.txt");


        try (BufferedReader in = new BufferedReader(new FileReader(file));

             BufferedWriter out = new BufferedWriter(new FileWriter(tmp))) {

            String str;


            while ((str = in.readLine()) != null) {

                if (str.startsWith(curName))

                    str = newName + str.substring(str.indexOf(','));


                out.write(str);

                out.newLine();

            }

        }


        System.out.println("remove old file: " + file.delete());

        System.out.println("rename temp file: " + tmp.renameTo(file));

    }


    public static void main(String... args) throws IOException {

        AddressBookManager addressBookManager = new AddressBookManager(new File("d:/addressBook.txt"));


        String curName = "oleg";

        String newName = getNewName(curName);

        addressBookManager.modifyContact(curName, newName);

    }


    private static String getNewName(String curName) {

        try (Scanner scan = new Scanner(System.in)) {

            System.out.print("Enter new name for (" + curName + "): ");

            return scan.nextLine();

        }

    }


}


查看完整回答
反對 回復 2023-11-01
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

問題是當您使用系統關閉掃描儀時。來自系統的輸入流也被關閉。因此,即使您使用 System.in 創建一個新的掃描儀,您也將無法重用該掃描儀。如果您使用的是 java 7,您可以使用 try 和資源來通過 Java 本身關閉所有 autocCleasable 資源。這將解決該問題。


    public static void modifyContact(String namee) {


        File file = new File("addressBook.txt");        

        try (Scanner sca = new Scanner(System.in);

            Scanner sc = new Scanner(file); 

            FileWriter pw = new FileWriter(file, true);) {

            String[] s;

            boolean foundPerson = false;

            String newName = sca.nextLine();

            while (sc.hasNextLine()) {

                s = sc.nextLine().split(",");

                if (s[0].equals(namee)) {

                    s[0] = s[0].replace(s[0], newName);

                    System.out.println("Name is " + namee + " phone number is " + s[1] + " ,address is " + s[3]

                            + " and email is " + s[2]);

                    foundPerson = true;

                    deleteByName(namee);

                    pw.write(s[0] + "," + s[1] + "," + s[2] + "," + s[3]);

                }

            }

            if (!foundPerson) {

                System.out.println("No contact found with " + namee);

            }

        } catch (IOException ex) {

            // System.out.println(ex.getMessage());

        }

    }


查看完整回答
反對 回復 2023-11-01
?
森欄

TA貢獻1810條經驗 獲得超5個贊

我在循環后添加

sc.close();
deleteByName(namee);

看起來效果很好。謝謝大家的幫助。


查看完整回答
反對 回復 2023-11-01
  • 5 回答
  • 0 關注
  • 254 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號