2017-04-05 45 views
-3

構建一個可幫助用戶練習添加的Java程序。使用添加方法,我添加了我的代碼,如下所示。這是給我布爾錯誤。此外,它會在用戶輸入名稱後運行,然後出現錯誤。Java - 方法和最終變量

UPDATED

錯誤命令提示符:

CAI.java:46: error: missing return statement 
    } 
    ^
1 error 

CAI.java

import java.util.Scanner; 
import java.util.Random; 

public class CAI 
{ 
    static Scanner input = new Scanner(System.in); 

    static int addition; 

    //main method 
    public static void main(String[] arguments) 
    { 
     //declare variables 
     String name; 
     int addition; 
     int subtraction; 
     int multiplication; 
     boolean = true; 

     //welcome the user 
     System.out.println("Welcome to Computer Assisted Instruction"); 

     //get the user's name 
     System.out.print("Enter your name: "); 
     name = input.next(); 

     System.out.printf("Hi %s. Let's practice addition!", name); 
    } 


    private static boolean addition() 
    { 
     //generate double digit numbers positive and negative 
     int number = 0; 
     //Addition 
     System.out.printf("What is %d + %d? ", number); 
     addition = input.nextInt(); 
    } 



} 

回答

0

首先,你必須初始化變量:

int number = 0; 

你不能使用System.out.println這樣,你必須使用System.out.printf代替了詮釋你必須使用:

System.out.printf("What is %d + %d? ", number); 

和字符串必須使用:

System.out.printf("Hi %s. Let's practice addition!", name); 

你的方法應該返回一個booleanreturn true : false;

第四不能用來初始化變量存在於另一種方法,而不是你可以把它放在你的類像這樣的屬性:

public class MainM { 

    static Scanner input = new Scanner(System.in); 

    static int addition;//<----------------------- 

    //main method 
    public static void main(String[] arguments) { 

第五你不應該讀與一個int next(),您必須使用nextInt()

+0

'CAI.java:43:錯誤:找不到符號 addition = input.next(); ^ 符號:變量加法 位置:類CAI 1錯誤' –

+0

檢查第4和第5點@TevelZaki –

+0

'CAI。Java的:46:錯誤:缺少return語句 } ^ 1 error' –

2
System.out.printf("Hi %d. Let's practice addition!", name); 

這裏的名字是字符串不是整數。使用%s

 System.out.printf("Hi %s. Let's practice addition!", name); 
+0

謝謝你的工作! –

+0

歡迎您..您可以upvote /接受您找到有用的答案。 – stinepike

0

%d用於數字值。但是名字是String所以使用%S代替

+0

謝謝你的回答! –

+0

不客氣:) –

0

輸出歡迎消息的System.out.printf應該具有%s而不是%d,%d是整型參數,而不是字符串。