2013-10-16 61 views
1

我一直在編碼一個有趣的小程序,但我已經收到此錯誤:找不到符號if語句錯誤

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找不到字符串變量,但是爲什麼? 該變量已定義,並且打印語句正確。

+2

Java iS CaS e SenSiTivE。 – Maroun

回答

5

java中沒有string類。有String班。

string dtext = "Two"; 

應該

String dtext = "Two"; 

S必須是大寫。

並看看你的字符串variable範圍。你是它僅限於如果block .Move它頂部,

然後你的代碼看起來像

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

你有錯字

String dtext = "One"; 

String class

一個件事檢查variable scope

if (day == 1) 
{ 
    String dtext = "One"; //it dtext has local scope here 
}//after this line dtext is not available 

聲明dtextif作爲

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

字符串不存在於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);