【问题标题】:How to debug the Java error "return cannot convert from java.lang.String to int"如何调试Java错误“return cannot convert from java.lang.String to int”
【发布时间】:2018-09-11 03:26:02
【问题描述】:

在第一种方法中,我收到此错误:

return 无法从 java.lang.String 转换为 int

我们试图解决它,但我们不知道该怎么做。该方法将一个String f 作为参数表示文件的名称。这个方法的目的是读取文件,它会返回一个带有文件内容的字符串。

这是我的代码:

import java.util.Scanner;
import java.io.*;
public class Encryption02{
  public static void main(String[] args)throws IOException{

    Scanner input = new Scanner(System.in);
    System.out.println("Enter the name of the file");
    String f = input.nextLine();
    String s = " ";

    readFile(f);
    writeToFile(f,s);
  }
  public static int getUnicode(char c){
    int unicode = (int) c;
    return c;
  }
  public static int readFile(String f)throws IOException{
    Scanner input = new Scanner(new File(f));

    while(input.hasNext()){
      f = input.nextLine();
      String a= String.valueOf(f);
     return f;
    }
  }
  public static void writeToFile(String f, String s)throws IOException{
    Scanner input = new Scanner(new File(f));
    PrintWriter output = new PrintWriter(""+f+"Output.txt");
    while(input.hasNext()){
      f = input.nextLine();
      for(int i = 0; i < f.length(); i++){
        int x = f.charAt(i);
        output.println(x);
      }
      output.println();
    }
    output.close();
  }
  public static void removeLastChars(String s){
   System.out.println(s.substring(0, 4)); 
  }
}

【问题讨论】:

  • 那么什么不能正常工作 - 是具体的。
  • 方法 int readFile(String f)。该错误表示返回无法从 java.lang.String 转换为 int。
  • 这个问题被严重否决,可能有几个原因。你有机会从这些原因中学习,这样你的下一个问题就更清楚了,这应该确保它被更好地接受。 (1) 始终使用有用的标题,这是对您的问题的简洁描述。 (2) 总是准确地解释错误是什么。 (3) 寻求具体的帮助,而不仅仅是模糊的“帮助”,尽量不要给读者留下你希望他们为你工作的印象。
  • 对不起,这是我第一次使用这个网站。我的错。

标签: arrays string file methods


【解决方案1】:

您必须检查readFile() 功能。 while 循环仅返回第一行的值。您也没有在 s 变量中分配任何值。

我已编辑您的代码以使 readFile 正常工作。您可以在下面查看:

注意:我用过StringBuilder,它比String好。

public static void main(String[] args)throws IOException{

   Scanner input = new Scanner(System.in);
   System.out.println("Enter the name of the file");
   String f = input.nextLine();
   String s = " ";

   s = readFile(f); // Edited this line
   writeToFile(f,s);
}
...
public static String readFile(String f)throws IOException{ // Edited the return type
   Scanner input = new Scanner(new File(f));

   StringBuilder sb = new StringBuilder();

   while(input.hasNext()){ // Edited the while loop
      f = input.nextLine();
      String a= String.valueOf(f);

      sb.append(a);

      if(input.hasNext())
         sb.append("\n");
      }

   return sb.toString();
 }

【讨论】:

  • 非常感谢!非常感谢!
  • @ChristianDeLuna 如果您认为答案有帮助,请接受(点击绿色复选框),您也会获得一些代表。
猜你喜欢
  • 2022-12-02
  • 1970-01-01
  • 2015-07-22
  • 2016-12-06
  • 2022-11-25
  • 2013-11-09
  • 1970-01-01
  • 2020-03-28
  • 2013-09-11
相关资源
最近更新 更多