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

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

For 循環和 parseInt 導致線程“main”中出現異常

For 循環和 parseInt 導致線程“main”中出現異常

慕少森 2023-07-28 16:45:36
我正在嘗試格式化字符串序列“ab c”,其中 ab 和 c 都是整數。我需要將 ab 和 c 添加到 3 個單獨的數組中。這就是我所擁有的。當提示輸入 str 時,不斷出現 NumberFormatException 錯誤。我嘗試更改一些變量及其聲明,并在線查看其他解釋。import java.util.*;import javax.swing.*; public static void main(String[] args){     Scanner s = new Scanner(System.in);     System.out.println("How Many times do you want to loop it?"); //Scanner takes in input     int loop = s.nextInt();     //if someone can help me format this better or have a 3d array that would be helpful.     ArrayList<Integer> a1 = new ArrayList<Integer>(); //3 arrays     ArrayList<Integer> b1 = new ArrayList<Integer>();     ArrayList<Integer> c1 = new ArrayList<Integer>();     String a = ""; //Int #1     String b = ""; //Int #2     String c = ""; //Int #3     String strSpc = " "; //String Spaces to compare with actual String     int x = 0;     String str = " ";     //Start of the error     for(int i=0; i<loop;i++) {         str = JOptionPane.showInputDialog(i+1 + ": ");         //checks format         while(str.charAt(x) !=(strSpc.charAt(0))){             a = a + str.charAt(x);             x++;         }         int a2 = Integer.parseInt(a);         a1.add(a2);         while(str.charAt(x+1) !=(strSpc.charAt(0))){             b = b+str.charAt(x);             x++;         }         int b2 = Integer.parseInt(b);         b1.add(b2);         while(str.charAt(x+1) !=(strSpc.charAt(0))){             c = c+str.charAt(x);             x++;         }         int c2 = Integer.parseInt(c);         c1.add(c2);         System.out.print('\n');     }}
查看完整描述

1 回答

?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

您似乎明白,當第一個 while 循環完成時,str.charAt(x)將是一個空格,因此在第二個 while 循環中,您首先檢查str.charAt(x+1),跳過空格。然而,在正文中,您仍在添加str.charAt(x),b這本來是一個空格。


 while(str.charAt(x+1) !=(strSpc.charAt(0))){ // x + 1 here

     b = b+str.charAt(x); // x here

     x++;

 }

你應該將其更改為:


 while(str.charAt(x+1) !=(strSpc.charAt(0))){ // x + 1 here

     b = b+str.charAt(x+1); // x + 1 here as well

     x++;

 }

第三個 for 循環也是如此。這次,它需要檢查charAt(x+2)并追加charAt(x+2)到c,因為charAt(x+1)那時已經是一個空格了。


x = 0;最后但并非最不重要的一點是,您需要在外循環的每次迭代開始時重置for。


 int x = 0; <---- move this....

 String str = " ";


 for(int i=0; i<loop;i++) {

    <---- here

     str = JOptionPane.showInputDialog(i+1 + ": ");

事實上,你所做的只是拆分str,可以通過以下方法完成split:


String[] splits = str.split(" ");

int a = Integer.parseInt(splits[0]);

int b = Integer.parseInt(splits[1]);

int c = Integer.parseInt(splits[2]);

a1.add(a);

b1.add(b);

c1.add(c); 


查看完整回答
反對 回復 2023-07-28
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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