while循环中的Java切换

时间:2015-12-01 11:37:37

标签: java

我有以下JAVA代码,其中案例在NIO应用程序的Runnable中。

作为应用程序的一部分,我正在尝试解码myBuffer的内容

  while  ((bytesRead = myChannel.read(myBuffer)) > 0) {
      myBuffer.flip();
      myBuffer.mark();

      //... do stuff ...

      switch (myType) {
           case '1':
                 // ... read buffer and do stuff ...
                break;
           case '2':
                // ... read buffer and do stuff ...
                break;
      }
  }
  // I should not be here

我注意到中断而不是破坏了switch语句,打破了while循环,将我发送到I should not be here

有没有办法阻止此行为并将进程发送回myBuffer.flip()?

完整的代码在这里:

https://github.com/trixpan/nifi-lumberjack-bundle

4 个答案:

答案 0 :(得分:3)

我对上面发布的答案感到惊讶,我认为我对java如何运行代码有一些误解,而break可能会破坏while循环,但我尝试使用简单的java代码段清除误解:

Random r = new Random();
    while  (true) 
    {
        System.out.println(" Inside while");
        int myType = r.nextInt();

        switch (myType) {
        case 1:
            // ... read buffer and do stuff ...
            break;
        case 2:
            // ... read buffer and do stuff ...
            break;
        default :
        break;
        }
    }
    System.out.println(" Outside while");

令我惊讶的是,Java代码在行System.out.println(" Outside while");上提出异常,说无法访问的代码

因此,我确信您的问题中的while因条件while ((bytesRead = myChannel.read(myBuffer)) > 0)而导致breakswitch以外的erminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' *** First throw call stack: 声明错误{/ 1}}

答案 1 :(得分:3)

您的actual code上写着:

 public class CategoryBaseAdapter extends BaseExpandableListAdapter  {              
private Context mContext;        
private HashMap<String, List<ProfessionChildEntity>> mListDataChild;                     private ArrayList<ProfessionEntity> mListDataGroup;
   private HashMap<Integer, boolean[]> mChildCheckStates;           
    private ChildViewHolder childViewHolder;
            private GroupViewHolder groupViewHolder;
            private String groupText;

            private String childText; 
     public CategoryBaseAdapter(Activity context,ArrayList<ProfessionEntity>listDataGroup, HashMap<String, List<ProfessionChildEntity>> listDataChild) {

 mContext = context;

 mListDataGroup = listDataGroup;
 mListDataChild = listDataChild;

 mChildCheckStates = new HashMap<Integer, boolean[]>();}

                    @Override
                    public boolean areAllItemsEnabled() {
                        return true;
                    }

                    @Override
                    public int getGroupCount() {
                        return mListDataGroup.size();
                    }

                    /*  
                     * This defaults to "public object getGroup" if you auto import the methods
                     * I've always make a point to change it from "object" to whatever item
                     * I passed through the constructor
                    */ 
                    @Override
                    public ProfessionEntity getGroup(int groupPosition) {
                        return mListDataGroup.get(groupPosition);
                    }

                    @Override
                    public long getGroupId(int groupPosition) {
                        return groupPosition;
                    }

                    @Override
                    public View getGroupView(int groupPosition, boolean isExpanded,
                            View convertView, ViewGroup parent) {
                        groupText = getGroup(groupPosition).getDecription();
                        if (convertView == null) {
                            LayoutInflater inflater = (LayoutInflater) mContext                                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                            convertView = inflater.inflate(R.layout.group_item, null);

                                groupViewHolder = new GroupViewHolder();
        groupViewHolder.mGroupText = (CheckBox) convertView.findViewById(R.id.groupTextView);

                            convertView.setTag(groupViewHolder);
                        } else {

                            groupViewHolder = (GroupViewHolder) convertView.getTag();
                        }

                        groupViewHolder.mGroupText.setText(groupText);

                        return convertView;
                    }

                    @Override
                    public int getChildrenCount(int groupPosition) {
                        return mListDataChild.get(mListDataGroup.get(groupPosition).getUsesr_type()).size();
                    }

                    @Override
        public ProfessionChildEntity getChild(int groupPosition, int childPosition) {                   return mListDataChild.get(mListDataGroup.get(groupPosition).getDecription()).get(childPosition);
                    }

                    @Override
                    public long getChildId(int groupPosition, int childPosition) {
                        return childPosition;
                    }

                    @Override
                    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

                        final int mGroupPosition = groupPosition;
                        final int mChildPosition = childPosition;

                        childText = getChild(mGroupPosition, mChildPosition).getDescription();

                        if (convertView == null) {

                            LayoutInflater inflater = (LayoutInflater) this.mContext
                                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                            convertView = inflater.inflate(R.layout.child_item, null);

                            childViewHolder = new ChildViewHolder();

                            childViewHolder.mChildText = (TextView) convertView
                                    .findViewById(R.id.childTextView);

                            childViewHolder.mCheckBox = (CheckBox) convertView
                                    .findViewById(R.id.checkBox);

                            convertView.setTag(R.layout.child_item, childViewHolder);

                        } else {

                            childViewHolder = (ChildViewHolder) convertView
                                    .getTag(R.layout.child_item);
                        }

                        childViewHolder.mChildText.setText(childText);
                        childViewHolder.mCheckBox.setOnCheckedChangeListener(null);

                        if (mChildCheckStates.containsKey(mGroupPosition)) {

                            boolean getChecked[] = mChildCheckStates.get(mGroupPosition);                           childViewHolder.mCheckBox.setChecked(getChecked[mChildPosition]);
                } else {
                            boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
                        mChildCheckStates.put(mGroupPosition, getChecked);
              childViewHolder.mCheckBox.setChecked(false);
                        }

                        childViewHolder.mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                if (isChecked) {

                                    boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
                getChecked[mChildPosition] = isChecked;
                    mChildCheckStates.put(mGroupPosition, getChecked);

                                } else {

                boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
                            getChecked[mChildPosition] = isChecked;
                            mChildCheckStates.put(mGroupPosition, getChecked);
                }
               }
                public void onCheckedChanged(RadioGroup group, int checkedId) {

}
});              return convertView;}   @Override public boolean isChildSelectable(int groupPosition, int childPosition) {
                return true;
                }
                @Override
                public boolean hasStableIds() {
                    return true;
                }   
                public final class GroupViewHolder {
                    CheckBox mGroupText;
               }
               public final class ChildViewHolder     
               TextView mChildText;
                CheckBox mCheckBox;
       }        
    }   

此消息的内容不正确 - 内部循环。

您的主要问题可能在于:

public class Signup_catgegory2 extends Activity {
                ExpandableListView listView1;
                ArrayList<ProfessionEntity> listProfession = new ArrayList<ProfessionEntity>();
                List<ProfessionChildEntity> listChildProfession=new ArrayList<ProfessionChildEntity>();
                DatabaseHandler databaseHandler;
                String typeOfUser;
                HashMap<String, List<ProfessionChildEntity>> listDataChild;
                Context context = null;
                CategoryBaseAdapter adapter;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_signup_category);
                    listView1=(ExpandableListView)findViewById(R.id.listView1);
                    InitDatabase();
                    Intent in = getIntent();
                    typeOfUser = in.getStringExtra("typeOfUser");
                    loadProfessionData(typeOfUser);
                    /*listChild.put("parent_key",listChildProfession);
                    listDataChild.add(listChild);*/
                    adapter=new CategoryBaseAdapter(Signup_catgegory2.this, listProfession,listDataChild);
                    listView1.setAdapter(adapter);
                }

                private void loadProfessionData(String pos) {
                    listProfession = databaseHandler.getParentCategory(typeOfUser);
                    ArrayList<String> list = new ArrayList<String>();
                    for (int i = 0; i < listProfession.size(); i++) {
                        Log.d("prfoession:", listProfession.get(i).getDecription());
                        list.add("" + listProfession.get(i).getDecription());
                        loadChildProfessionData(i);
                    }

                }
                private void loadChildProfessionData(int pos) {
                    listChildProfession = databaseHandler.getPChildCategory(pos);
                    String parent_key=String.valueOf(pos);
                    List<ProfessionChildEntity> list = new ArrayList<ProfessionChildEntity>();
                    for (int i = 0; i < listChildProfession.size(); i++) {
                        //for(int j=0;j<listChildProfession.size();j++){
                        Log.d("prfoession:", listChildProfession.get(i).getDescription());
                        list.add(listChildProfession.get(i).getDescription());
                    //}

                    }
                    listDataChild.put(parent_key,list);
                }
                private void InitDatabase() {
                    // TODO Auto-generated method stub
                    try {
                        databaseHandler = new DatabaseHandler(Signup_catgegory2.this);
                        databaseHandler.createdatabase();

                    } catch (IOException ioe) {
                        throw new Error("Unable to create database");
                    }
                    try {
                        databaseHandler.opendatabase();
                    } catch (SQLException sqle) {
                        throw sqle;
                    }
                }
            }

由于NIO是异步的,public ArrayList<ProfessionChildEntity> getPChildCategory(int Parent_key){ ArrayList<ProfessionChildEntity> flashcardentity=new ArrayList<ProfessionChildEntity>(); String selectQuery="SELECT * FROM "+"Child WHERE Parent_key ="+"'"+Parent_key+"'"; Log.d("selectQuery",selectQuery); Cursor cursor=db.rawQuery(selectQuery, null); Log.d("Cusorfav","c"+cursor.getCount()+""+selectQuery); if(cursor.moveToFirst()){ do{ Log.d("cursorfav", "cinside"); ProfessionChildEntity pce=new ProfessionChildEntity(); pce.setUser_type(cursor.getString(0)); pce.setChild_key(cursor.getInt(2)); pce.setDescription(cursor.getString(3)); flashcardentity.add(pce); }while(cursor.moveToNext()); } return flashcardentity; } 很可能会返回logger.info("We are outside the loop and position is " + String.valueOf(socketBuffer.position())); 。 Thjis并未表示cahnnel已完成 - 这只表示此时频道中没有更多数据。你应该真的使用:

while  ((bytesRead = myChannel.read(myBuffer)) > 0)

自己处理read案例。

答案 2 :(得分:1)

你可以使用一个标签,它会教你如何标记一个循环,但是在这个例子中没有它,它的工作方式是相同的:

        while  ((bytesRead = myChannel.read(myBuffer)) > 0) {
              myBuffer.flip();
              myBuffer.mark();

              //... do stuff ...

              choose: switch (myType) {
                   case '1':
                         // ... read buffer and do stuff ...
                        break choose;
                   case '2':
                        // ... read buffer and do stuff ...
                        break choose;
                   }
              }
              // I should not be here
}

但它工作正常,案件中的突破只打破案件,你的时间可能已经结束,你被这种情况所取代。

答案 3 :(得分:1)

myChannel.read(myBuffer)不能保证读取myBuffer的全长,你需要写出更好的阅读方法,以确保你完全填满myBuffer,这可能就是原因。