计算连续数字

时间:2015-09-26 20:52:16

标签: java loops scope

我目前仍然坚持如何计算用户输入的连续数字。我正在尝试CancellationTokenSource cancellation_token_source = new CancellationTokenSource(); CancellationToken cancellation_token = cancellation_token_source.Token; BlockingCollection<string> blocking_collection = new BlockingCollection<string>(10); using (StreamReader reader = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read))) { using ( StreamWriter writer = new StreamWriter(new FileStream(success_filename, FileMode.OpenOrCreate, FileAccess.Write))) { var input_task = Task.Factory.StartNew(() => { try { while (!reader.EndOfStream) { if (cancellation_token.IsCancellationRequested) return; blocking_collection.Add(reader.ReadLine()); } } finally //In all cases, even in the case of an exception, we need to make sure that we mark that we have done adding to the collection so that the Parallel.ForEach loop will exit. Note that Parallel.ForEach will not exit until we call CompleteAdding { blocking_collection.CompleteAdding(); } }); try { Parallel.ForEach(blocking_collection.GetConsumingEnumerable(), (line) => { bool test_reault = Test(line); if (test_reault) { lock (writer) { writer.WriteLine(line); } } }); } catch { cancellation_token_source.Cancel(); //If Paralle.ForEach throws an exception, we inform the input thread to stop throw; } input_task.Wait(); //This will make sure that exceptions thrown in the input thread will be propagated here } } ,但a=lastvariable保持为0.我知道变量范围,但如何更改lastvariable

a=lastvariable

4 个答案:

答案 0 :(得分:1)

以这种方式改变你的while循环。你做了一个小错误,没有设置lastvariable。

while(input>0){ System.out.print("Give a positive #: "); int a = scan.nextInt(); if(a==lastvariable) consecutive++; if (a<0) input = 0; lastvariable = a; //small correction here }

答案 1 :(得分:0)

试试这个:

if (a<0) input = 0;
lastvariable = a;

答案 2 :(得分:0)

您永远不会将lastvariable设置为其他值。

    a = lastvariable;

表示将a设置为lastvariable中存储的值,但不是相反。

答案 3 :(得分:0)

a = lastvariable;

a分配给lastvariable的值,在您当前的代码中,该值始终为0。你必须这样做:

lastvariable = a;