首页 \ 问答 \ 为什么这个随机Next()抛出异常?(Why does this random Next() throw an exception?)

为什么这个随机Next()抛出异常?(Why does this random Next() throw an exception?)

嗨,我是编程新手,正在阅读本书。 这是其中一章的结尾处的练习。 但是我的代码抛出了这个异常。

        Random rand = new Random();
        List<int> numbers = new List<int>();

        for (int i = 0; i < 1000; i++)
        {
            numbers[i] = rand.Next(1, 1001);
        }

        for (int i = 0; i < numbers.Count; i++)
        {
            listBox1.Items.Add(numbers[i]);
        }

这是错误: 在此处输入图像描述


Hi I'm new to programming and am working from this book. This is an exercise at the end of one of the chapters. But my code throws this exception.

        Random rand = new Random();
        List<int> numbers = new List<int>();

        for (int i = 0; i < 1000; i++)
        {
            numbers[i] = rand.Next(1, 1001);
        }

        for (int i = 0; i < numbers.Count; i++)
        {
            listBox1.Items.Add(numbers[i]);
        }

Here is the error: enter image description here


原文:https://stackoverflow.com/questions/19358323
更新时间:2024-03-20 18:03

最满意答案

我相信这会有效,你在printer()函数中不需要return语句:

import sys
subjects = ["History", "Science"]
topics_science = ["Light", "X-mas Exam Review"]
topics_history = ["Italian Renaissance"]
science_xmasreview = ["Q. What do we use to catogorize a habitat?",
                      "A. Damp or Dry, Hot or Cold, Windy or Calm, Dim or Bright.",
                      "Q. What is something that only eats plants?",
                      "A. Herbivore",
                      "Q. What are the properties of oxygen?"]

science_light = [
    "Q. What is an object the gives out light?",
    "A. Light source",
    "Q. What is the speed of light?",
    "A. 300 million meters per second.",
    "Q. What does transparent mean?",
    "A. Light can pass completely through a transparent material."]

history_renaissance = [
    "Q. What did Lorenzo do differently from Cosimo?",
    "A. Lorenzo made no effort to conceal his power",
    "Q. Why did the Pope want Lorenzo dead?",
    "A. Because the Pope wanted more power and saw Lorenzo as a threat.",
    "Q. Who did the Pazzi plot with to kill Lorenzo?",
    "A. Pope Sixtus IV"]

def printer(list):
    n = 0
    l = len(list)
    print
    while n < l:
        print list[n]  # <-- Changed this from a return to a print statement
        newline()
        n += 1
    while n == l:
        n += 1

def qanda(x):
    print
    print "Enter 1 for just questions"
    print "Enter 2 for just answers"
    print "Enter 3 for both"
    qa = raw_input("Enter number: ")
    qa = str(qa)
    if qa == '1':
        printer(x[::2])
    elif qa == '2':
        printer(x[1::2])
    elif qa == '3':
        printer(x)
    else:
        print "Not recognized"

def newline():
    raw_input()
    print



def subjectchoice():
    if subject == "1":
        print
        history()
    elif subject == "2":
        print
        science()
    else:
        print 'Not recognized.'
def science():
    print topics_science
    print "Enter 1 for Light"
    print "Enter 2 for X-mas Exam Review"
    topicchoice = raw_input("Enter number: ")
    topicchoice = str(topicchoice)
    if topicchoice == "1":
        qanda(science_light)
    elif topicchoice == "2":
        qanda(science_xmasreview)
    else:
        print "Not recognized"
        sys.exit
def history():
    print topics_history
    print "Enter 1 for Italian Renaissance"
    topicchoice = raw_input("Enter number: ")
    topicchoice = str(topicchoice)
    if topicchoice == "1":
        return qanda(history_renaissance)
    else:
        print "Not recognized"
        sys.exit()
print subjects
print "Enter 1 for History"
print "Enter 2 for Science"
subject = raw_input("Enter number: ")
subject = str(subject)
subjectchoice()

I believe this will work, you didn't need the return statement in your printer() function:

import sys
subjects = ["History", "Science"]
topics_science = ["Light", "X-mas Exam Review"]
topics_history = ["Italian Renaissance"]
science_xmasreview = ["Q. What do we use to catogorize a habitat?",
                      "A. Damp or Dry, Hot or Cold, Windy or Calm, Dim or Bright.",
                      "Q. What is something that only eats plants?",
                      "A. Herbivore",
                      "Q. What are the properties of oxygen?"]

science_light = [
    "Q. What is an object the gives out light?",
    "A. Light source",
    "Q. What is the speed of light?",
    "A. 300 million meters per second.",
    "Q. What does transparent mean?",
    "A. Light can pass completely through a transparent material."]

history_renaissance = [
    "Q. What did Lorenzo do differently from Cosimo?",
    "A. Lorenzo made no effort to conceal his power",
    "Q. Why did the Pope want Lorenzo dead?",
    "A. Because the Pope wanted more power and saw Lorenzo as a threat.",
    "Q. Who did the Pazzi plot with to kill Lorenzo?",
    "A. Pope Sixtus IV"]

def printer(list):
    n = 0
    l = len(list)
    print
    while n < l:
        print list[n]  # <-- Changed this from a return to a print statement
        newline()
        n += 1
    while n == l:
        n += 1

def qanda(x):
    print
    print "Enter 1 for just questions"
    print "Enter 2 for just answers"
    print "Enter 3 for both"
    qa = raw_input("Enter number: ")
    qa = str(qa)
    if qa == '1':
        printer(x[::2])
    elif qa == '2':
        printer(x[1::2])
    elif qa == '3':
        printer(x)
    else:
        print "Not recognized"

def newline():
    raw_input()
    print



def subjectchoice():
    if subject == "1":
        print
        history()
    elif subject == "2":
        print
        science()
    else:
        print 'Not recognized.'
def science():
    print topics_science
    print "Enter 1 for Light"
    print "Enter 2 for X-mas Exam Review"
    topicchoice = raw_input("Enter number: ")
    topicchoice = str(topicchoice)
    if topicchoice == "1":
        qanda(science_light)
    elif topicchoice == "2":
        qanda(science_xmasreview)
    else:
        print "Not recognized"
        sys.exit
def history():
    print topics_history
    print "Enter 1 for Italian Renaissance"
    topicchoice = raw_input("Enter number: ")
    topicchoice = str(topicchoice)
    if topicchoice == "1":
        return qanda(history_renaissance)
    else:
        print "Not recognized"
        sys.exit()
print subjects
print "Enter 1 for History"
print "Enter 2 for Science"
subject = raw_input("Enter number: ")
subject = str(subject)
subjectchoice()

相关问答

更多
  • 因为您将stringstream设置为仅输入 - 无输出。 如果在尝试提取int后检查fail()位,您将看到它不起作用: s >> i; bool b = s.fail(); if( b ) cerr << "WHOA DOGGIE! WE BLOWED UP\n"; 在您的代码中,更改: stringstream s(ios::in); 至: stringstream s; Because you set the stringstream to input-only -- ...
  • 我相信这会有效,你在printer()函数中不需要return语句: import sys subjects = ["History", "Science"] topics_science = ["Light", "X-mas Exam Review"] topics_history = ["Italian Renaissance"] science_xmasreview = ["Q. What do we use to catogorize a habitat?", ...
  • 以下是有关您的代码的几条评论: 您从未向任何视图添加任何约束,因此您不应删除它们。 iOS(CocoaTouch)将这些约束添加到这些视图中,因此请不要触摸它们。 (换句话说: 当你没有调用addConstraint时不要调用removeConstraint )。 您对约束的控制是激活和停用它们。 将添加和删除留给iOS。 激活约束时,会将约束(通过iOS)添加到约束中提到的两个项目的最常见祖先。 因此,如果两个视图是兄弟,它将被添加到父视图。 如果两个视图是父视图和子视图,则约束将添加到父视图。 如果两个 ...
  • 这是我的建议。 在循环的每次迭代中创建'major_array'并在该数组中添加'part_result'。 这样,如果你的循环迭代10次,那么你将在'major_array'中添加10个数组。 最后,当for循环结束时返回数组。 :) def readTXT(): #create a new array major_array = [] part_result = [] '''Reading all data from text file''' with open ...
  • @CarstenKönig链接中使用的措辞使我意识到我正在查找错误的文档。 问题确实是,启动服务器实现的线程是前台线程,将其更改为后台线程会导致ThreadPool实现按预期运行。 ECMA标准似乎推迟了特定的终止行为(CLI文档也没有提及它的任何内容)。 我仍然在寻找能否找到一个更详细地描述整个终止程序的通用文档。 The wording used in the @Carsten König's link lead me to realize I was looking in the wrong docu ...
  • odbc_fetch_array和odbc_fetch_row都会从结果中拉出行。 尝试改为: $conn = odbc_connect('MoeinODBCTest1', '', ''); $sql = "select * from Products"; $rs = odbc_exec($conn, $sql); while($arr = odbc_fetch_array($rs)) { print_r($arr); echo ' '; } Both odbc_fetch_array a ...
  • reduce(set.intersection, (set(x) for x in [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]])) reduce(set.intersection, (set(x) for x in [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]))
  • 就像将H放入一个列表来统一字符代码一样,您需要使用[R]以便返回的字符代码列表与列表统一: english2133t([],[]). english2133t([H|T], [R|E]):- translate([H],[R]), english2133t(T,E). Just as you enclose H into a list to unify character codes, you need to use [R] so that the returned list of charact ...
  • 这对我来说看起来像编译器限制。 getTypes总是返回List ,因此使用原始HelloWorld类型应该没有区别。 也就是说,这两种解决方案中的任何一种都可以克服错误: 创建一个参数化类型的HelloWorld而不是原始类型: for (Type type : new HelloWorld().getTypes() ) { // any type will do, I chose ...
  • 问题其实很简单。 提示:以下代码以死锁结束。 package main import "fmt" func main() { var c chan string go func() { c = make(chan string) c <- "42" }() str := <-c fmt.Println(str) } 从那里,问题是微不足道的。 启动goroutine时,您的频道未初始化。 有两个goroutines的比赛,显然 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。