我如何使用java中的每个循环? [英] How do I use for each loop in java?

查看:64
本文介绍了我如何使用java中的每个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们不能通过键盘读取数组中的值,而使用for_each循环而不初始化数组吗?

请帮我怎么做?



我尝试过:



Can't we read the values in array through keyboard ,while using for_each loop without intialising the array?
Please help me how to do that?

What I have tried:

class Dcoder
{
	
public static void main(String args[])
throws java.io.IOException
{
int num[];
int sum = 0;
System.out.println(" enter number");
for(int i=0;i<5;i++)

num[i]=(int )System.in.read();
for(int x:num)

{
	sum+=x;
}

System.out.println("the sum is ;" +sum);
}}

推荐答案

int num[];

不分配数组,它声明一个名为 num 的变量,它可以指向一个整数数组。



要使用它,你必须分配一个包含正确数量元素的数组:

Does not allocate an array, it declares a variable called num that can "point to" an array of integers.

To use it, you must allocate an array containing the right number of elements:

int num[] = new int[5];


您的数组 num 未分配,因此您可以不为 num [i] 赋值。



你可以像这样初始化它:

Your array num is not assigned, so you can not assign values to num[i].

You can initialise it like so:
int num[] = new int[5];


这篇关于我如何使用java中的每个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆