从另一个方法传递变量值 [英] Passing variable values from another method

查看:138
本文介绍了从另一个方法传递变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经解决了这个问题好几个小时了,我已经取得了很大的进步(非常感谢搜索这个网站并应用类似问题中的提示)但我现在似乎陷入了僵局。请仔细看看我做了什么,并指出我出错的地方并提供伪造的代码来纠正,或者指出一个资源可以帮助我填补我理解的空白。我真的觉得我只是错过了一个小细节,这个细节会使这个主题对我有意义。

I've been working through this problem for several hours, and I've made significant progress (thanks in large part to searching this site and applying tips found in similar questions) but I now seem to be at an impasse. Please take a look through what I have done and either point out where I've gone wrong and provide psuedo code to correct, or point me to a resource that can help me by filling in the gap of my understanding. I really feel as though I'm just missing a tiny detail that will make this topic make sense to me.

该应用程序的目的是加,减,乘,并根据用户输入的2个分子和2个分母划分分数(是的,这是一个课程分配,所以请不要给出源代码,而是指出我在概念上出错的地方)。我把它分解为步骤,第一步是获取用户的输入并将其输出以进行确认。

The purpose of the application is to add, subtract, multiply, and divide fractions based on user input of 2 numerators and 2 denominators (yes, this is for a course assignment so please don't give source code but rather pointers on where I've gone wrong conceptually). I've broken it down into steps, the first of which is getting the user's input and outputting it back for confirmation.

方法文件:

package Fractions;
import java.util.Scanner;

public class FractionValues
{
    // Declare integer class variables for package Fractions
    int fracNum1;
    int fracDenom1;
    int fracNum2;
    int fracDenom2;

    // Obtain four integers from user input and output to console as two fractions
    public static void getFractions(int fracNum1, int fracDenom1, int fracNum2, int fracDenom2)
    {
        Scanner inInt = new Scanner(System.in);

        System.out.println("Enter an integer for the numerator of the first " +
                                    "fraction:  ");
            fracNum1 = inInt.nextInt();

        System.out.println("Enter an integer for the denominator of the first " +
                                    "fraction:  ");
            fracDenom1 = inInt.nextInt();

        System.out.println("Enter an integer for the numerator of the second " +
                                    "fraction:  ");
            fracNum2 = inInt.nextInt();

        System.out.println("Enter an integer for the denominator fo the second " +
                                    "fraction:  ");
            fracDenom2 = inInt.nextInt();
        System.out.println("===================================================" +
                                    "=================");
    }

    // Return values of variables from input for use in other classes
    public int getFracNum1()        {return fracNum1;}
    public int getFracDenom1()      {return fracDenom1;}
    public int getFracNum2()        {return fracNum2;}
    public int getFracDenom2()      {return fracDenom2;}    
}  

main方法文件:

package Fractions;
public class TestFractions2
{
    public static void main(String[] args)
    {
        // Call getFractions method to assign variables from user input
        FractionValues newFracNum1 = new FractionValues();
        newFracNum1.getFracNum1();

        FractionValues newFracDenom1 = new FractionValues();
        newFracDenom1.getFracDenom1();

        FractionValues newFracNum2 = new FractionValues();
        newFracNum2.getFracNum2();

        FractionValues newFracDenom2 = new FractionValues();
        newFracDenom2.getFracDenom2();

        System.out.println("You entered " + newFracNum1.getFracNum1() + "/" + newFracDenom1.getFracDenom2() + " and " +
                                     newFracNum2.getFracNum2() + "/" + newFracDenom2.getFracDenom2() + " as your fractions.");
    }
}

至少在一些挣扎之后,这两个文件现在都在编译。但是,该应用程序不起作用。这是我得到的输出:

At least after some struggles, both files now compile. However, the application doesn't work. This is the output I get:

你输入了0/0和0/0作为分数。

You entered 0/0 and 0/0 as your fractions.

一旦这部分工作,我将添加一个if语句,提示用户回复是否继续他们的选择,或返回条目提示。

Once this part works, I'll be adding an if statement prompting the user to respond whether they wish to continue with their choices, or return to the entry prompts.

根据以下有价值的反馈和作业的限制,我得到以下信息:

Based on the valuable feedback below and the constraints of the assignment, I've gotten the following:

package Fractions;
import java.util.Scanner;

public class FractionValues
{
    int fracNum1;
    int fracDenom1;
    int fracNum2;
    int fracDenom2;

    Scanner inInt = new Scanner(System.in);

    // Obtain four integers from user input
    public int getFracNum1()
    {
        System.out.println("Enter an integer for the first numerator:  ");
        return fracNum1 = inInt.nextInt();
    }

    public int getFracDenom1()      
    {
        System.out.println("Enter an integer for the first denominator:  ");
        return fracDenom1   = inInt.nextInt();
    }

    public int getFracNum2()
    {
        System.out.println("Enter an integer for the second numerator:  ");
        return fracNum2     = inInt.nextInt();
    }

    public int getFracDenom2()
    {
        System.out.println("Enter an integer for the second denominator:  ");
        return fracDenom2   = inInt.nextInt();
    }
}

以及主要的申请方法:

package Fractions;
public class TestFractions2
{
    public static void main(String[] args)
    {
        // Call FractionValues methods to assign variables from user input
        FractionValues newFracNum1 = new FractionValues(); 
        FractionValues newFracDenom1 = new FractionValues(); 
        FractionValues newFracNum2 = new FractionValues(); 
        FractionValues newFracDenom2 = new FractionValues(); 

        System.out.println("You entered " + newFracNum1.getFracNum1() + "/" + 
                newFracDenom1.getFracDenom2() + " and " + newFracNum2.getFracNum2() +
                "/" + newFracDenom2.getFracDenom2() + " as your fractions."); 
    }
}

两个文件都正确编译,我得到以下预期输出:

Both files compile properly, and I get the following expected output:

输入第一个分子的整数:

2
输入第二个分母的整数:

5
输入第二个分子的整数:

6
输入第二个分母的整数:

3
您输入的分数为2/5和6/3。

Enter an integer for the first numerator:
2 Enter an integer for the second denominator:
5 Enter an integer for the second numerator:
6 Enter an integer for the second denominator:
3 You entered 2/5 and 6/3 as your fractions.

非常感谢你非常适合您对方法和构造函数的帮助,以及对命名约定的建设性意见。您的评论带给我的地方很可能会让我从考试失败中解脱出来!即使在非常耐心的朋友的帮助下,我也一直在努力使用这个概念。

Thank you very much for your help with methods and constructors, and constructive comments on naming conventions. The places your comments led me have very likely taken me from failing my exam to acing it! I've been struggling with this concept for weeks, even with the help of a very patient friend.

推荐答案

代码存在一些问题。首先,您看到的输出是 toString()的默认实现的产物,该实现位于 Object 类中(从中可以获得包括 GetFractions 在内的所有类。重写此方法以返回实例的字符串表示形式:

There are a few problems with the code. First, the output you see is the product of the default implementation of toString() that is found in Object class (from which all classes including GetFractions ultimately derive). Override this method to return string representation of your instances:

@Override
public String toString() {
  return ...
}

public static void main(String[] args) {
  ...
  System.out.println("..." + newFracNum1 + "...");
}

或者不是将实例传递给 System.out .println()传递成员访问方法调用的结果(此类方法称为getter):

or instead of passing the instance to System.out.println() pass a result of a member access method call (such methods are known as getters):

public double getSomeValue() {
  return ...
}

public static void main(String[] args) {
  ...
  System.out.println("..." + newFracNum1.getSomeValue() + "...");
}

请注意 double 和其他原始类型将自动转换为字符串。

Note that double and other primitive types will automagically be converted to strings.

其次,静态 GetFractions()方法修改其参数这是无效的(没有人会看到变化,因为他们通过价值传递)。该方法应该修改现有实例的同名实例变量,然后它不应该是静态的,或者它应该是一个工厂方法,根据用户提供的数据创建新实例,在这种情况下,它会将值传递给构造函数或者它应该是一个构造函数本身。无论哪种方式,您都不希望修改方法的参数。以下是三种解决方案的概述:

Second, your static GetFractions() method modifies its arguments which is ineffective (nobody will see the change since they're passed by value). The method should either modify same-named instance variables of an existing instance and then it should not be static or it should be a factory method creating new instances based on the data provided by the user in which case it would pass the values to a constructor or it should be a constructor itself. Either way, you don't want to modify the method's parameters. Here is the outline of the three solutions:

从输入流中读取数据的非静态方法:

Non-static method which reads data in from an input stream:

public void fromStream(InputStream inStream) {
  // Read data from inStream into instance variables fracNum1, fracDenom1,...
}

静态工厂方法:

public static GetFractions fromStream(InputStream inStream) {
  int fracNum1,... ;
  // Read data from inStream into local variables fracNume1, ...
  return new GetFractions(fracNum1, ...);
}

构造函数:

public GetFractions(InputStream inStream) {
  // Read data from inStream to initialize instance variables fracNum1, fracDenom1,...
}

另请注意,将 InputStream 传递给所有这些方法可提供比硬编码更大的灵活性 System.in

Notice also that passing an InputStream into all these methods affords greater flexibility than hardcoding System.in.

第三,您应该重新考虑您的命名约定。尽可能调用与类相同的静态方法通常是一种不好的做法。此外,建议使用带有动词表达式的名词表达式和方法来调用类和对象。这有助于设计类并使代码更具可读性。 GetFractions 更适合作为方法的名称而不是类。 分数会产生更好的类名。

Third, you should reconsider your naming convention. Calling a static method the same as the class, while possible, is generally a bad practice. Also, it's advisable to call classes and objects with noun expressions and methods with verb expressions. This helps to design your classes and makes the code more readable. GetFractions is more suitable as a name of a method rather than a class. Fractions would make for a better class name.

这篇关于从另一个方法传递变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆