1

我一直在编写一个有趣的小程序,但我收到了这个错误:

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找不到字符串变量,但是为什么呢?变量已定义,打印语句正确。

4

3 回答 3

5

java中没有string类。有字符串类。

string dtext = "Two";

应该

   String dtext = "Two";

S必须是资本。

并查看您的 Stringvariable范围。您将其限制为 If block.Move it to top,

然后你的代码看起来像

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);
于 2013-10-16T14:48:47.847 回答
1

你有错字

String dtext = "One";  

String类

另一件事检查变量范围

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);
于 2013-10-16T14:49:02.710 回答
1

java中不存在字符串。你的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);
于 2013-10-16T14:49:12.977 回答