質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
ファイル

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Q&A

解決済

1回答

3156閲覧

nullを読み込んだ時、別の文字列を表示させたい

taka0145

総合スコア7

ファイル

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

0グッド

1クリップ

投稿2022/01/21 16:17

前提・実現したいこと

・前提
機能としては、主に情報の入力と情報の表示の2つです。
メニュー1では、codeとnameを入力させて、Informationをnewし、mapに入れて、ファイルに書き込んでいます。
メニュー2では、ファイルから読み取ったcode,nameを表示、それに対応するnumberを入力させ、mapに入れ、ファイルに書き込んでいます。
メニュー3ではファイルを読み込み、表示させています。
メニュー1では、numberを入力しないのでnullをセットしているのですが、一度終了させて、
メニュー3を実行しようとすると、nullを読み込めずエラーが出てしまいます。

・実現したいこと
numberを入力していない場合は、「未入力」と表示させたいです。

発生している問題・エラーメッセージ

Exception in thread "main" java.lang.ExceptionInInitializerError at Main.main(Main.java:26) Caused by: java.lang.NumberFormatException: Character n is neither a decimal digit number, decimal point, nor "e" notation exponential mark. at java.base/java.math.BigDecimal.<init>(BigDecimal.java:511) at java.base/java.math.BigDecimal.<init>(BigDecimal.java:394) at java.base/java.math.BigDecimal.<init>(BigDecimal.java:827) at Filer.getInventory(Filer.java:24) at EntryData.<clinit>(EntryData.java:19) ... 1 more

該当のソースコード

java

1import java.math.BigDecimal; 2 3public class Information { 4 private String code; 5 private String name; 6 private BigDecimal number ; 7 8 public Information(String code, String name, BigDecimal number){ 9 this.code = code; 10 this.name = name; 11 this.number = number; 12 } 13 14 public String getCode() { 15 return this.code; 16 } 17 public String getName() { 18 return this.name; 19 } 20 public BigDecimal getNumber() { 21 return this.number; 22 } 23 24 public void setCode(String code) { 25 this.code = code; 26 } 27 public void setName(String Name) { 28 this.name = name; 29 } 30 public void setNumber(BigDecimal number) { 31 this.number = number; 32 } 33}

java

1import java.io.IOException; 2import java.io.InputStreamReader; 3import java.io.BufferedReader; 4 5class Main { 6 public static void main(String[] args) throws IOException { 7 8 BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 9 boolean end = false; 10 11 while (!end) { 12 try { 13 System.out.println(""); 14 System.out.println("<<メニュー>>"); 15 System.out.println("1:code,name入力 \n2:number入力 \n3:表示 \n4:終了"); 16 System.out.print(">"); 17 int choice = Integer.parseInt(input.readLine()); 18 System.out.println(""); 19 switch (choice) { 20 case 1: 21 EntryData.enter(); 22 break; 23 24 case 2: 25 EntryData.input(); 26 break; 27 28 case 3: 29 File.show(); 30 break; 31 32 case 4: 33 end = true; 34 break; 35 } 36 } catch (IOException e) { 37 System.out.println("指定された値を入力してください。"); 38 } catch (NumberFormatException e) { 39 System.out.println("数字を入力してください。"); 40 } 41 } 42 } 43}

java

1import java.io.BufferedReader; 2import java.io.BufferedWriter; 3import java.io.File; 4import java.io.FileInputStream; 5import java.io.FileNotFoundException; 6import java.io.FileOutputStream; 7import java.io.IOException; 8import java.io.InputStreamReader; 9import java.io.OutputStreamWriter; 10import java.io.PrintWriter; 11import java.util.ArrayList; 12import java.math.BigDecimal; 13import java.util.HashMap; 14import java.util.Map; 15 16class EntryData { 17 18 public static HashMap<String, Information> stockMap = Filer.getInventory(); 19 20 public static void enter() throws IOException { 21 boolean finish = false; 22 BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 23 24 System.out.print("codeを入力してください\n>"); 25 String code = input.readLine(); 26 System.out.print("nameを入力してください\n>"); 27 String name = input.readLine(); 28 29 Information information = new Information(code, name, null); 30 stockMap.put(information.getCode(),information); 31 filewrite(); 32 33 } 34 35 public static void input() throws IOException { 36 37 BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 38 for (String key : stockMap.keySet()) { 39 System.out.println("code:" + key); 40 System.out.println("name:" + stockMap.get(key).getName()); 41 System.out.print("■numberを入力してください\n>"); 42 BigDecimal number = new BigDecimal(input.readLine()); 43 44 stockMap.get(key).setNumber(number); 45 } 46 filewrite(); 47 } 48 49 public static void filewrite() { 50 51 try (PrintWriter dataFile = new PrintWriter(new BufferedWriter 52 (new OutputStreamWriter(new FileOutputStream("StockData.csv"), "UTF-8")))) { 53 54 for(Map.Entry<String, Information> stock : stockMap.entrySet()) { 55 dataFile.println(stock.getValue().getCode() + "," + stock.getValue().getName() + 56 "," + stock.getValue().getNumber()); 57 } 58 } catch (FileNotFoundException e) { 59 System.out.println("ファイルがみつかりませんでした。確認してください。"); 60 return; 61 } catch (IOException e) { 62 System.out.println("指定された値を入力しているか確認してください。"); 63 return; 64 } 65 } 66}

java

1import java.io.BufferedReader; 2import java.io.BufferedWriter; 3import java.io.FileInputStream; 4import java.io.FileNotFoundException; 5import java.io.FileOutputStream; 6import java.io.IOException; 7import java.io.InputStreamReader; 8import java.io.OutputStreamWriter; 9import java.io.PrintWriter; 10import java.math.BigDecimal; 11import java.util.HashMap; 12import java.util.Map; 13 14public class Filer { 15 16 public static HashMap<String, Information> getInventory() { 17 18 HashMap<String, Information> map = new HashMap<String, Information>(); 19 String text; 20 21 try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("StockData.csv"), "UTF-8"))) { 22 while((text = br.readLine()) != null) { 23 String[] st = text.split(",",-1); 24 BigDecimal st2 = new BigDecimal(st[2]); 25 Information information = new Information(st[0], st[1], st2); 26 map.put(information.getCode(),information); 27 } 28 } catch (FileNotFoundException e) { 29 System.out.println("指定されたファイルが見つかりません。"); 30 } catch (IOException e) { 31 System.out.println("指定された値を入力しているか確認してください。"); 32 } 33 return map; 34 } 35 36 public static void show() { 37 String line; 38 try (BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream("StockData.csv"), "UTF-8"))) { 39 while ((line = file.readLine()) != null) { 40 String[] data = line.split(",", 0); 41 for (String elem : data) { 42 System.out.println(elem); 43 } 44 } 45 } catch (FileNotFoundException e) { 46 System.out.println("指定されたファイルが存在するか確認してください。"); 47 } catch (IOException e) { 48 System.out.println("値が入力されているか確認してください。"); 49 } 50 } 51}

試したこと

メニュー1でnull以外をセットしようとしましたが、エラーが出ます。
また、numberはBigDecimal型なので「未入力」という文字列はセットできず、手詰まりの状態です。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jimbe

2022/01/21 16:44

バグがあり、コンパイルが通りません。
guest

回答1

0

ベストアンサー

まずこのような場合はファイルとマップを管理するクラスを想定したほうが簡単になると思います。
以下ではファイル名に沿って StockData クラスがファイルの読み書きとマップの管理を担当しています。

number に関しましては、現状は表示だけですので BigDecimal で保持する必要は無く String で持ってしまうのも一つの手かと思います。
以下では、文字列の number を BigDesimal に変換する処理を Information のコンストラクタが行うようにし、 enter 時の null 指定はそのまま、 input 時の null 以外指定時は BigDescimal に変換しています。
また、 Information は変更不可とし、 input 時は新たに Information を作成しています。

null 時の "未入力" 表示は、 Information.getNumberString() によって「表示用の number 」を返すことで行っています。(ついでにファイルにも"未入力"と書くようにしましたが、これは余計かもしれません。)

java

1import java.io.*; 2import java.math.BigDecimal; 3import java.util.*; 4 5class Information { 6 static final String NULL_NUMBER_STRING = "未入力"; 7 8 final String code; 9 final String name; 10 final BigDecimal number; 11 12 Information(String code, String name, String number) { 13 this.code = code; 14 this.name = name; 15 this.number = toBigDecimal(number); 16 } 17 18 private BigDecimal toBigDecimal(String number) { 19 if(number == null) return null; 20 try { 21 return new BigDecimal(number); 22 } catch(NumberFormatException ignore) { 23 //無視 24 } 25 return null; 26 } 27 28 String getNumberString() { 29 return number == null ? NULL_NUMBER_STRING : ""+number; 30 } 31 32 @Override 33 public String toString() { 34 return "code="+code+", name="+name+", number="+getNumberString(); 35 } 36} 37 38class StockData { 39 private String filename; 40 private String charsetName; 41 private Map<String, Information> map = new HashMap<>(); 42 43 StockData(String filename, String charsetName) throws IOException { 44 this.filename = filename; 45 this.charsetName = charsetName; 46 loadFile(); 47 } 48 49 Set<Information> getValues() { 50 return new HashSet<Information>(map.values()); 51 } 52 53 void put(Information info) throws IOException { 54 map.put(info.code, info); 55 saveFile(); 56 } 57 58 void showAll() { 59 for(Information info : map.values()) { 60 System.out.println(info); 61 } 62 } 63 64 private void loadFile() throws IOException { 65 map.clear(); 66 try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), charsetName))) { 67 for(String line; (line = br.readLine()) != null; ) { 68 String[] st = line.split(",", -1); 69 if(st.length == 3) { 70 Information information = new Information(st[0], st[1], st[2]); 71 map.put(information.code, information); 72 } 73 } 74 } catch(FileNotFoundException ignore) { 75 //無視 76 } 77 } 78 79 private void saveFile() throws IOException { 80 try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), charsetName))) { 81 for(Information info : map.values()) { 82 pw.println(info.code+","+info.name+","+info.getNumberString()); 83 } 84 } 85 } 86} 87 88public class Main { 89 public static void main(String[] args) throws IOException { 90 91 StockData stockData = new StockData("StockData.csv", "UTF-8"); 92 93 BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 94 95 for(boolean end=false; !end; ) { 96 try { 97 System.out.println(); 98 System.out.println("<<メニュー>>"); 99 System.out.print("1:code,name入力\n2:number入力\n3:表示\n4:終了\n>"); 100 int choice = Integer.parseInt(input.readLine()); 101 System.out.println(); 102 switch(choice) { 103 case 1: 104 enter(stockData, input); 105 break; 106 107 case 2: 108 input(stockData, input); 109 break; 110 111 case 3: 112 stockData.showAll(); 113 break; 114 115 case 4: 116 end = true; 117 break; 118 119 default: 120 System.out.println("指定された値を入力してください。"); 121 } 122 } catch(NumberFormatException e) { 123 System.out.println("数字を入力してください。"); 124 } catch(IOException e) { 125 e.printStackTrace(); 126 } 127 } 128 } 129 130 static void enter(StockData stockData, BufferedReader input) throws IOException { 131 System.out.print("codeを入力してください\n>"); 132 String code = input.readLine(); 133 System.out.print("nameを入力してください\n>"); 134 String name = input.readLine(); 135 136 stockData.put(new Information(code, name, null)); 137 } 138 139 static void input(StockData stockData, BufferedReader input) throws IOException { 140 for(Information info : stockData.getValues()) { 141 System.out.println("code:" + info.code); 142 System.out.println("name:" + info.name); 143 System.out.print("■numberを入力してください\n>"); 144 String number = input.readLine(); 145 146 stockData.put(new Information(info.code, info.name, number)); 147 } 148 } 149} 150

投稿2022/01/21 18:04

編集2022/01/21 18:15
jimbe

総合スコア12543

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

taka0145

2022/01/22 00:59

ありがとうございます。 nullの変換以前に、クラスやメソッドの役割の分け方から間違っていると気づかされました。 ご返信いただいたコードを参考に自身でもう一度やってみたいと思います。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問