我输入一个类似于1234的数字。我需要偶数位置值和奇数位置值,并且我已经存储在数组列表中,像偶数位置数组列表值是2和4,.In奇数组列表值是1和3,当我将数组列表值2和4相乘时,.But都工作得很好,我得到了2600.请帮帮忙
import java.util.*;
public class list {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Character> list1 = new ArrayList<>();
List<Character> list2 = new ArrayList<>();
System.out.print("Enter Distance ");
String no = sc.next();
for(int i = 0 ; i < no.length() ; i++){
if(i % 2 != 0){
list1.add(no.charAt(i));
}else{
list2.add(no.charAt(i));
}
}
for (char 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);
}
}发布于 2019-05-25 19:49:54
你是在乘以字符而不是数字,这就是为什么你会得到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);
}
}发布于 2019-05-25 18:37:48
您正在将int与Character相乘。因此,字符会自动转换为整数,但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)发布于 2019-05-25 18:35:37
您应该将字符转换为整数值:
for (int i=0; i < list1.size() ; i++ ) {
tot = tot * Integer.valueOf(list1.get(i).toString());
}https://stackoverflow.com/questions/56303916
复制相似问题