Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

java - How to access the method in another method?

In this code, i am not able to call the user() method in facto1() method but I am not able to access the value of n in for loop

import java.util.*;    
public class fecto {
    //Scanner sc = new Scanner(System.in);
    //int n;
    
    public int user() {
        Scanner sc = new Scanner(System.in);
        int n;
        System.out.println("Enter the number:");
        n = sc.nextInt();
        return n;
    }
    
    public int facto1() {
        int i, fac = 1;
        //int p = user();
        //System.out.println(p);
        user()
        for (i = 0; i <= n; i++) {
            fac = fac * i;
        }
        return fac;
    }
    
    public static void main(String[] args) {
        fecto fe = new fecto();
        fe.facto1();
    }
}
question from:https://stackoverflow.com/questions/65948645/how-to-access-the-method-in-another-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The call to user() does not store the result locally. Change

//int p = user();
//System.out.println(p);
user()
for (i = 0; i <= n; i++) {

to

int n = user(); // <-- you want `n`, not `p`.
for (i = 1; i <= n; i++) { // <-- 0 * x == 0, do not start with i = 0

Further, in main you aren't printing the result.

fecto fe = new fecto();
int result = fe.facto1();
System.out.println(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...