我已经阅读了具有相同标题的其他问题,但没有一个对我的问题有帮助,在线也没有任何帮助。
我是 Java 的新手,正在尝试运行一个基本程序,但我不断收到上述错误。
下面的代码。
package loopy;
import java.io.*;
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String input = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
toggleStringCase(input);
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
上面写着 toggleStringCase(input);是我在尝试将变量传递给函数时遇到错误的地方。
我读过的任何内容都表明我可能做错了什么。
我确定这一定是一个基本错误,但有人可以指出正确的方向吗。
我是否在某处遗漏了一些语法?
最佳答案
input
仅在 try
block 中有范围,将调用移到那里。此外,我更喜欢 try-with-resources
而不是使用另一个 try block 显式关闭 in
。 但是,需要注意的是关闭in
也会关闭System.in
(这是一个全局变量),操作时要格外小心所以(因为以后任何从 System.in
读取的尝试都会失败)
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
String input = in.readLine();
toggleStringCase(input);
} catch (IOException e) {
e.printStackTrace();
}
关于Java - "varible name"无法解析为变量 - 我找不到我的错误所在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015658/