为什么会出现索引超出范围错误?错误如下,
Why do I get index out of range error? The error is as follows,
这里是错误:
我的代码:
def isVariable(line):
modifier = ['private','protected','public']
datatype = ['String','int','float','boolean']
status = False
linelist = list(line.split())
if(linelist[0] in modifier):
if(linelist[1] in datatype):
if(';' in linelist[len(linelist)-1]):
status = True
return status
else:
return status
f = open('Student.java','r')
vList = []
for line in f:
status = isVariable(line)
if status == True:
vList.append(line)
print(vList)
怎么了?
你得到错误是因为在那行代码中,
linelist
是空的,因此,您无法获取列表的第一个 (index 0
) 元素。
它可能为空的原因是文件中有空行。
您的文件中似乎有一行是空的,因此调用 list(line.split())
returns 一个空列表。因此,不存在第零个元素,包含 IndexError
。您可以添加一些 try ... except ...
块来处理此错误。尝试:
def isVariable(line):
modifier = ['private','protected','public']
datatype = ['String','int','float','boolean']
status = False
linelist = list(line.split())
try:
has_modifier = linelist[0] in modifier
except IndexError:
return status
try:
has_datatype = linelist[1] in datatype
except IndexError:
return status
try:
has_semicolon = ';' in linelist[-1]
except IndexError:
return status
if(has_modifier and has_datatype and has_semicolon):
status = True
return status
else:
return status
f = open('Student.java','r')
vList = []
for line in f:
status = isVariable(line)
if status == True:
vList.append(line)
print(vList)
这里是错误:
我的代码:
def isVariable(line):
modifier = ['private','protected','public']
datatype = ['String','int','float','boolean']
status = False
linelist = list(line.split())
if(linelist[0] in modifier):
if(linelist[1] in datatype):
if(';' in linelist[len(linelist)-1]):
status = True
return status
else:
return status
f = open('Student.java','r')
vList = []
for line in f:
status = isVariable(line)
if status == True:
vList.append(line)
print(vList)
怎么了?
你得到错误是因为在那行代码中,
linelist
是空的,因此,您无法获取列表的第一个 (index 0
) 元素。
它可能为空的原因是文件中有空行。
您的文件中似乎有一行是空的,因此调用 list(line.split())
returns 一个空列表。因此,不存在第零个元素,包含 IndexError
。您可以添加一些 try ... except ...
块来处理此错误。尝试:
def isVariable(line):
modifier = ['private','protected','public']
datatype = ['String','int','float','boolean']
status = False
linelist = list(line.split())
try:
has_modifier = linelist[0] in modifier
except IndexError:
return status
try:
has_datatype = linelist[1] in datatype
except IndexError:
return status
try:
has_semicolon = ';' in linelist[-1]
except IndexError:
return status
if(has_modifier and has_datatype and has_semicolon):
status = True
return status
else:
return status
f = open('Student.java','r')
vList = []
for line in f:
status = isVariable(line)
if status == True:
vList.append(line)
print(vList)