我一直在为一个小程序编写代码,但我收到了这个错误:
Compilation error time: 0.11 memory: 380672 signal:0Main.java:22:
error: cannot find symbol
string dtext = "One";
^
symbol: class string
location: class Ideone
Main.java:37: error: cannot find symbol
System.out.println(dtext);
^
symbol: variable dtext
location: class Ideone
2 errors
我的代码:
import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.String;
class Ideone
{
public static void main (String str[]) throws IOException
{
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the month of birth");
//int month = sc.nextInt();
System.out.println("Please enter the day of birth");
int day = sc.nextInt();
//day num to day text
if (day == 1)
{
string dtext = "One";
}
else if (day == 2)
{
string dtext = "Two";
}
else if (day == 3)
{
string dtext = "Three";
}
else
{
System.out.println("Error, day incorrect.");
}
System.out.println(dtext);
}
}
我做了一些研究,发现java找不到字符串变量,但为什么呢?
定义了变量,并且print语句是正确的。
答案 0 :(得分:5)
java中没有string
类。有String类。
string dtext = "Two";
应该是
String dtext = "Two";
S
必须是资本。
查看您的String variable
范围。您被限制为block
。将其移至顶部,
然后您的代码看起来像
String dtext = "";
if (day == 1) {
dtext = "One";
} else if (day == 2) {
dtext = "Two";
} else if (day == 3) {
dtext = "Three";
} else {
System.out.println("Error, day incorrect.");
}
System.out.println(dtext);
答案 1 :(得分:1)
你有拼写错误
String dtext = "One";
还有一件事要检查variable scope
if (day == 1)
{
String dtext = "One"; //it dtext has local scope here
}//after this line dtext is not available
在dtext
之外声明if
为
String dtext = "";
if (day == 1)
{
dtext = "One";
}
else if (day == 2)
{
dtext = "Two";
}
else if (day == 3)
{
dtext = "Three";
}
else
{
System.out.println("Error, day incorrect.");
}
System.out.println(dtext);
答案 2 :(得分:1)
字符串。您的string
首字母应为首字母 - > String
例如
将string dtext = "One";
更改为String dtext = "One";
从您的代码中
if (day == 1)
{
string dtext = "One";
}
else if (day == 2)
{
string dtext = "Two";
}
else if (day == 3)
{
string dtext = "Three";
}
else
{
System.out.println("Error, day incorrect.");
}
System.out.println(dtext); //this line will get error dtext variable in not reachable.
您的代码需要如下所示
String dtext ="";
if (day == 1)
{
dtext = "One";
}
else if (day == 2)
{
dtext = "Two";
}
else if (day == 3)
{
dtext = "Three";
}
else
{
System.out.println("Error, day incorrect.");
}
System.out.println(dtext);