3 回答

TA貢獻1872條經驗 獲得超4個贊
你乘以字符而不是數字,這就是你得到 2600 的原因。在將它們相乘之前將你的字符轉換為數字。這是更新的代碼。
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list1 = new ArrayList<>();//changed here
List<Integer> list2 = new ArrayList<>();//changed here
System.out.print("Enter Distance ");
String no = sc.next();
try{
Integer.parseInt(no);
}catch(Exception e ) {
System.out.println("NumberFormatException");
return;
}
for(int i = 0 ; i < no.length() ; i++){
if(i % 2 != 0){
list1.add(Character.getNumericValue(no.charAt(i)));//changed here
}else{
list2.add(Character.getNumericValue(no.charAt(i)));//changed here
}
}
for (int c : list1 ) {
System.out.println(c);
}
int tot = 1;
for (int i=0; i < list1.size() ; i++ ) {
tot = tot * list1.get(i);
}
System.out.print(tot);
}
}

TA貢獻1810條經驗 獲得超4個贊
您正在將Characters 與 h相乘int。所以字符會自動轉換為整數,但 java 獲取這些字符的 ASCII 值(例如 '0' == 48)。因為 '2' 的 ASCII 值是 50 作為整數,而 '4' 的值是 52 作為整數,所以當它們相乘時你得到 2600。
您可以通過替換“0”值來簡單地將 ASCII 值轉換為整數值:
tot = tot * (list1.get(i) - '0');
你可以使用 java 8 stream API 來做你想做的事:
int tot = no.chars() // Transform the no String into IntStream
.map(Integer.valueOf(String.valueOf((char) i))) // Transform the letter ASCII value into integer
.filter(i -> i % 2 == 0) // remove all odd number
.peek(System.out::println) // print remaining elements
.reduce(1, (i, j) -> i * j); // multiply all element of the list (with the first value of 1)

TA貢獻1820條經驗 獲得超9個贊
您應該將字符轉換為整數值:
for (int i=0; i < list1.size() ; i++ ) {
tot = tot * Integer.valueOf(list1.get(i).toString());
}
添加回答
舉報