如何在Java中添加数字?

时间:2015-12-14 13:18:20

标签: java

我的第一个Java项目差不多完成了,但只有一件事情让我困扰:我需要加上数字。但我无法做到。这是代码:

package dieses.programm.wird.getestet;

import java.util.Scanner;

public class NewClass {
    public static void main(String[] args) {

        System.out.println("Zahl eingeben: ");
        Scanner scanner = new Scanner(System.in);
        String data = scanner.nextLine();
        System.out.println(data);

        int a = 0;

        while (a < 6) {
            System.out.println(a);
            a++;
        }

        if (a > 6) {
            System.out.println("SAFE SPACE");

        } else {
            System.out.println("SAVED");
            System.out.println("GOOD EVENING");
        }
        String s = new String("Alte Noten: ");
        String t = new String("5.5");
        String u = new String("4");
        String v = new String("3");
        String w = new String("2.5");
        String x = new String("6.0");
        String y = new String("5.2");
        String z = new String("4");

        String t1 = t.replaceAll("5.5", "6");
        String u1 = u.replaceAll("4", "4");
        String v1 = v.replaceAll("3", "5");
        String w1 = w.replaceAll("2.5", "3");
        String x1 = x.replaceAll("6.0", "2");
        String y1 = y.replaceAll("5.2", "1.8");
        String z1 = z.replaceAll("4", "4.4");
        System.out.println("Neu: " + s + " " + t1 + " " + u1 + " " + v1 + " " + w1 + " " + x1 + " " + y1 + " " + z1);
        System.out.println("Neue Noten eingeben: ");

        Scanner scanner1 = new Scanner(System.in);
        String data1 = scanner.nextLine();
        System.out.println(data1);
        System.out.println("Zusammengerechnet: t1 + u1 + v1 + w1 + x1 + y1 + z1");
    }
}

2 个答案:

答案 0 :(得分:2)

如果它是困扰你的最后一行,Java在打印之前不会解释你的字符串。您需要更换

System.out.println("Zusammengerechnet: t1 + u1 + v1 + w1 + x1 + y1 + z1");

double sum = Double.parseDouble(t1) + Double.parseDouble(u1)
    + Double.parseDouble(v1) + Double.parseDouble(w1)
    + Double.parseDouble(x1) + Double.parseDouble(y1)
    + Double.parseDouble(z1);
System.out.println("Zusammengerechnet: " + sum);

答案 1 :(得分:0)

要将数字添加到一起,您需要将它们转换为intfloat。由于你有小数,你应该使用浮点数。

在字符串上调用它以获得浮点数:

float t2 = Float.parseFloat(t1);

这会将t1保存的字符串转换为浮点数。然后,您可以像以下一样添加浮动:

t2 + u2 + v2 + w2 + x2 + y2 + z2