简体   繁体   English

为什么会出现索引超出范围错误? 错误如下,

[英]Why do I get index out of range error? The error is as follows,

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. linelist为空,因此您无法获取列表的第一个(索引0元素。

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.看起来您文件中的其中一行是空的,因此调用list(line.split())返回一个空列表。 So, there is no zeroth element, casing the IndexError .因此,没有第零个元素,包含IndexError You can add some try... except... blocks which will handle this error.您可以添加一些try... except...块来处理此错误。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM