Here is the error:
My code:
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)
What is wrong?
You get the error because in that line of code,
linelist
is empty, and so, you cannot get the first (index 0
) element of the list.
The reason a it can be empty is empty lines in the file.
It looks like one of the lines in your file is empty, so calling list(line.split())
returns an empty list. So, there is no zeroth element, casing the IndexError
. You can add some try... except...
blocks which will handle this error. Try:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.