简体   繁体   English

将for循环外的值/值传递给变量 - java :: processing

[英]Passing a value/values outside of for loop to a variable - java :: processing

I am looking how to pass the value word and its corresponding count to be saved into a variable outside the for loop. 我正在寻找如何将值字及其相应的计数传递给for循环外的变量。 My code is currently: 我的代码目前是:

import java.util.Iterator; 
import java.util.*;


import com.google.common.collect.ImmutableMultiset; 
import com.google.common.collect.Multiset; 
import com.google.common.collect.Multisets; 

ImmutableMultiset<String> top = null;

void setup() { 
   size(800, 480); 
   smooth(); 

   String[] data = loadStrings("data/data.txt");

   ImmutableMultiset<String> myMultiset = ImmutableMultiset.copyOf(data); 

   top = Multisets.copyHighestCountFirst(myMultiset); 

   Iterator it = top.entrySet().iterator(); 

   for (int i = 0; (i < 5) && it.hasNext(); i++) { 
      Multiset.Entry entry = (Multiset.Entry) it.next(); 

      String word = (String) entry.getElement(); 
      int count = entry.getCount(); 

      System.out.println(word + " -> " + count);
   }
}

I need these values to apply them to a bar chart in my draw() function. 我需要这些值将它们应用到我的draw()函数中的条形图。

You can declare the variables in your class and not locally in your enhanced loop. 您可以在类中声明变量,而不是在增强循环中本地声明。

eg 例如

private String word;
private int count;

and use getters to call them 并使用getter来调用它们

eg 例如

public String getWord(){ return word; }

To expand on Murat's answer, this is a matter of variable scoping. 为了扩展穆拉特的答案,这是一个变量范围问题。 Anything declared within the for loop block (between the {} bounds) will only be visible within this block. 在for循环块中(在{}边界之间)声明的任何内容将仅在此块中可见。

If you declare the count variable outside the for loop block, you will be able to use it within the scope of the block that contains the for loop; 如果在for循环块之外声明count变量,则可以在包含for循环的块的范围内使用它; in this case the setup method. 在这种情况下是设置方法。

Murat's example will allow you to obtain the value of this variable from anywhere, whether it's within this or some other class. Murat的例子允许您从任何地方获取此变量的值,无论是在此类还是其他类中。

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

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