2015-12-14 30 views
-7

我的第一個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"); 
    } 
} 
+0

什麼是你的問題/問題? – Jens

+0

請描述「但我不能做」部分。 –

+0

你真的想要輸出什麼?你想做什麼可能是一個正確的要求,但你的程序看起來非常糟糕。 – aProgrammer

回答

0

到了數字加在一起,你需要把它們變成intfloat。既然你有小數,你應該使用浮點數。

調用此弦上獲得浮動:

float t2 = Float.parseFloat(t1); 

這將打開保存在t1成浮動的字符串。然後,您可以添加花車一起想:

t2 + u2 + v2 + w2 + x2 + y2 + z2 
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);