在这里,我有另一个基本问题,按照我的上一个问题。我希望这些问题不会让任何人烦恼,因为它们非常基本。 首先我将名称作为输入然后将它们更改为整数然后我需要将它们相加并将它们放入等式中,此Sum不起作用
先谢谢你的时间和帮助。
package loveindex;
import java.util.Scanner;
import java.lang.Math;
public class LoveIndex {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
testi = testi.toUpperCase();
char[] ascii1 = testi.toCharArray();
for(char ch:ascii1){
// System.out.println((int)ch+" ");
int[] a = {(int)ch};
int all = IntStream.of(a).sum(); // >>> here it shows an error and the quick fix as always is just a bigger mess ...
System.out.println("The sum is " + a);
}
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
testi2 = testi2.toUpperCase();
char[] ascii2 = testi2.toCharArray();
for(char ch:ascii2){
System.out.println((int)ch+" ");
}
scan.close();
}
}
答案 0 :(得分:2)
你想这样做吗?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
testi = testi.toUpperCase();
char[] ascii1 = testi.toCharArray();
int sum = 0;
for (char ch : ascii1) {
sum += ch;
}
System.out.println("Sum: " + sum);
scan.close();
}
根据要求,持续投入的示例:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
while (scan.hasNext()) {
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
testi = testi.toUpperCase();
char[] ascii1 = testi.toCharArray();
int sum = 0;
for (char ch : ascii1) {
sum += ch;
}
System.out.println("Sum: " + sum);
}
scan.close();
}
答案 1 :(得分:1)
你要重新声明变量" a"在你宣布它之后。当你只是将一个char转换为int时,你也不需要将int [] a声明为数组。我会在每个循环中移动到你的外部并将其初始化为0.然后在每个循环之外移动系统打印的总和。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
testi = testi.toUpperCase();
char[] ascii1 = testi.toCharArray();
int a = 0;
for(char ch:ascii1){
// System.out.println((int)ch+" ");
a += (int)ch;
}
System.out.println("The sum is " + a);
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
testi2 = testi2.toUpperCase();
char[] ascii2 = testi2.toCharArray();
for(char ch:ascii2){
System.out.println((int)ch + " ");
}
scan.close();
}
}
答案 2 :(得分:0)
即使您使用Java 8编译它,此代码也没有意义:
char[] ascii1 = testi.toCharArray();
for(char ch:ascii1){
// System.out.println((int)ch+" ");
int[] a = {(int)ch};
int all = IntStream.of(a).sum(); // >>> here it shows an error and the quick fix as always is just a bigger mess ...
System.out.println("The sum is " + a);
}
对于输入String的每个字符,您正在创建一个由单个字符组成的数组,然后计算该单个int的总和。
相反,您可能希望将所有字符加在一起:
char[] ascii1 = testi.toCharArray();
int sum = 0;
for(char ch:ascii1){
sum += ch;
}
System.out.println("The sum is " + sum);