繁体   English   中英

Java编程帮助

[英]Java Programming Help

我对此有点困惑,我不知道该如何解决这个问题,如果您能在这个问题上为我提供帮助,也许会告诉我需要做什么,以及如何解决,我将不胜感激。 问题是:

编写一个称为countChars的方法,该方法将InputStream作为参数,读取流并将其包含的字符数作为整数返回。 该方法中可能发生的任何IOExceptions应该传递回该方法的调用者。

请注意,方法标头应显示有可能发生异常。

我用以下代码尝试了这个问题:

public class countChars

{


public int countChars(int InputStream)
{
  return InputStream;

}


}

我收到一条错误消息,说:

Main.java:26: cannot find symbol
symbol  : method countChars(java.io.InputStream)
location: class Main
        s1 = "" + countChars(f1);
                  ^
1 error
public class CounterUtility
{
    public static Integer countChars(InputStream in)
    {
        Integer counter = 0;

        /* your code here */

        return counter;
    }
}

s1 = CounterUtility.countChars(f1).toString();

您有几件事混在一起。 首先,您的函数将接受一个I​​nputStream并返回一个int值。 您已将函数设置为接受一个称为InputStream的int并返回一个int。

InputStream具有read()函数,该函数加载流的下一个字符(如果没有剩余字符,则加载-1)。 您需要定义一个整数计数器,然后多次调用read()以获得-1的响应。 看到-1时,您就知道自己在流的末尾,可以返回计数器(计数器的值等于字符数)。

//take in an InputStream object and return an int
public int countChars(InputStream input){
   int counter = 0; //start counting at zero
   while (input.read() != -1){
       //as long as there are more characters, keep incrementing the counter
       counter++; //add one to the counter
   }
   return counter; //return the result
}

自从上大学以来,我从未尝试过编译以上代码,而且我还没有用Java编写过代码,因此可能存在语法错误。

您的countChars方法在名为countChars的类countChars
调用方法时,需要一个类的实例。

您需要使该方法static ,然后将调用更改为countChars.countChars(f1)

该错误可能是由于countChars方法未成功编译的事实造成的。 如果查看编译器的其余输出,则可能会在return语句中看到它的抱怨。 将存根return替换为return 0 ,它应该通过。

此外,您不应使用InputStream作为变量名。 使用is或类似的东西。

此外,如果方法应将InputStream作为参数,则签名应为

public int countChars(InputStream is) { ...

好像您正在编译错误的文件。 您包括的代码示例不包含错误消息中的代码。 因此,我得出的结论是,编译器未对您认为正确的源文件起作用(假设您已准确地复制/粘贴了正在使用的代码)。

首先,在Java中,类名应始终大写。

其次,您正在运行的代码在Main类中。 您的countChars方法在countChars类中。 您需要创建一个countChars对象以对其进行调用,或将countChars设为static方法,该方法将通过countChars.countChars(intHere)进行调用。

第三, int InputStream是一个名称为InputStream的整数值,而不是InputStream对象。

几点。 通常,将所有Java类都大写被认为是一种好习惯。 你是不是被迫这样做,但是当你不知道它让可读性变得更加困难了世界其他地区。

所以公共类countChars成为公共类CountChars

其次,你正试图调用对象的方法,但你不指定哪些对象要使用。 通常,您不能在面向对象的编程中单独使用方法,必须先指定类,然后再指定要在类上调用的方法。 这是通过以下两种方式之一完成的:

  1. 通过创建一个Object (类的实例)并在该Object上调用方法,如下所示:
 CountChars counter = new CountChars(); s1 = "" + counter.countChars(i); 
  1. 通过声明方法是静态的,这意味着它将是对“类”对象,方法CountChars 要调用静态方法,将使用类名,如下所示:
 s1 = "" + CountChars.countChars(i); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM