復習

朝に直面したエラー問題点

ifの条件式で、startIndex<0 && stopIndex>=0 である必要があった。

桁数が4で小分けにできない場合の処理を作成しておいたが、桁数が4で小分けにできる時、startIndex = 負の数、stopIndex=0の状態になるため、s.substring(0, 0)となり、文字列が空のものを数字に変換しようとしていたことに因る。

 

この点を受けて、次回より気をつけて行きたいこと。

エラーになっている直接の状況をしっかり確認する。要素や変数の値を出力してみて予期していない動きになっているかをチェックすることで気づけた可能性がある。

慣れなんだろうな。。。

public class Main {
public static void main(String[] args) {
//Sは4〜最大1000桁(数字の)文字列
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int t = Integer.parseInt(sc.nextLine());

int len = s.length();
int startIndex = len-4;
int stopIndex = len;
ArrayList<Integer> array = new ArrayList<>();
while(startIndex>=0) {
String num = s.substring(startIndex, stopIndex);
int x = Integer.parseInt(num);
//System.out.println(num);
array.add(x);
stopIndex = startIndex;
startIndex = startIndex - 4;
if(startIndex<0 && stopIndex>0) {
//System.out.println(s.substring(0, stopIndex));
String last = s.substring(0, stopIndex);
int y = Integer.parseInt(last);
array.add(y);
}
}
int up = 0;
ArrayList<Integer> array2 = new ArrayList<>();
for(int i=0; i<array.size(); i++){
int x = array.get(i);
int y = x * t;
//System.out.print(y);
//System.out.print(":");
int left = y % 10000;
//System.out.print(left + ":");
int sub = left + up;
//System.out.println(sub);
array2.add(sub);
up = y / 10000;
}
String result = "";
for(int i=array2.size()-1; i>=0; i--) {
result += array2.get(i);
}
System.out.println(result);
}
}