【问题标题】:can't find symbol, what am i doing wrong? [closed]找不到符号,我做错了什么? [关闭]
【发布时间】:2014-11-06 08:26:46
【问题描述】:

所以基本上我在我的 main 中调用了一个类,然后试图打印出底部的最后一行,但它一直说它找不到 int x 和 int y 的符号。我很确定我将它们相应地分配给正确的控制台输入。有谁知道我做错了什么。我是 Java 新手。

import java.util.*;

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

        Scanner console = new Scanner(System.in);
        Scanner console2 = new Scanner(System.in);        

        System.out.println("Enter a number for the numerator and denominator: ");

        //creates the first class object
        rationalNumbers rational = new rationalNumbers(console.nextInt(), console2.nextInt());

        int x = console.nextInt;
        int y = console2.nextInt;

        System.out.println("Rational Number is: " +x+ "/" +y);
    }
}

公开课

public class rationalNumbers {

private int Numerator;
private int Denominator;
private String String;



public rationalNumbers(int Numerator, int Denominator){

    if (Denominator==0)
        throw new IllegalArgumentException();
    this.Numerator=Numerator;
    this.Denominator=Denominator;

}

public void rationalNumber(){

}

public int getDenominator(){
    return Denominator;

}

public int getNumerator(){
    return Numerator;
}

public String toString(){
    return String;
}

}

【问题讨论】:

  • 1.为什么要使用两个单独的 Scanner 对象来访问相同的标准输入流?这不是必需的,您最好使用一台扫描仪。 2. 可能你的意思是这样的:int x =rational.x; int y = 理性.y; ?因为现在您读取两个数字,将它们存储在有理数中,并且永远不要使用有理数。然后你从控制台读取另外两个数字并打印它们。 3.约定类名中大写字母优先
  • 它甚至可以与 2 台扫描仪一起使用吗?
  • 是的,它使用两个扫描仪运行和编译,因为在我的课堂上是一个 int 分子和 int 分母,所以我知道如何为每个扫描仪使用两个单独的扫描仪的最好方法是因为我每次都需要不同的输入跨度>
  • 刚刚添加了我的类文件,它显示了我添加两个扫描仪的原因

标签: java class object int symbols


【解决方案1】:

应该是console.nextInt()而不是console.nextInt

您不必要地创建了两个 Scanner 对象 这应该更有意义

System.out.println("Enter a number for the numerator"); 
int x = console.nextInt();
System.out.println("Enter a number for the denominator"); 
int y = console.nextInt();
rationalNumbers rational = new rationalNumbers(x,y); //follow class naming convention
System.out.println("Rational Number is: " +x+ "/" +y);

【讨论】:

  • 这是个坏主意。您应该考虑方法调用的顺序。如果 OP 只是根据你的回答编辑他的代码,他不会得到预期的结果
  • @stealthjong 但预期的输出是什么?
  • 是的,我就是这个意思。
  • 我刚刚添加了我的类文件,这就是我使用两个扫描仪的原因
  • 那么如果你按照我说的做会有什么问题呢?顺便说一句,您的除法逻辑在哪里,您只是使用构造函数初始化字段
【解决方案2】:

nextInt() 是 Scanner 对象的一种方法(它的副作用是阻塞直到输入一行)。在对 rationalNumbers 类的构造函数的调用中,您相应地引用它,这很好。在xy 的定义中,您引用了一个不存在的nextInt 成员变量。您可以再次调用该方法,如

int x = console.nextInt();
int y = console2.nextInt();

在这种情况下,用户必须再输入两个数字。您可以在构造rationalNumbers 对象之前执行此操作,并将 x 和 y 重用于构造函数参数,以便打印您传递给有理对象的相同数字。

顺便说一句,您的示例中不需要两个不同的Scanner 对象;您可以将每次使用 console2 替换为 console 以获得相同的效果。

【讨论】:

  • 感谢您的建议
猜你喜欢
  • 2012-11-07
  • 2013-02-08
  • 2014-02-16
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 2021-01-05
  • 2018-01-22
  • 1970-01-01
相关资源
最近更新 更多