java如何循环输出数组?

如下面代码所示,我想让他跟string[] vertices={"C01","C02","C03","C04","C05",...};的功能一样,但是下面的这个程序好像不合适,大家帮我看一下,谢谢

Scanner reader=new Scanner(System.in);
int Input=reader.nextInt();
for(int n=1;n<=Input;n++){
vertices[n-1]= "C"+"n.toString()"; //带权有向图的顶点集合
}

有两种方法:
1. 使用三层循环遍历多维数组
public class Ransack {
public static void main(String[] args) {
int array[][][] = new int[][][]{ // 创建并初始化数组
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } },
{ { 13, 14, 15 }, { 16, 17, 18 } }
};
array[1][0][0] = 97; // 改变指定数组元素
for (int i = 0; i < array.length; i++) { // 遍历数组
for (int j = 0; j < array[0].length; j++) {
for (int k = 0; k < array[0][0].length; k++) {
System.out.print(array[i][j][k] + "\t");
}
System.out.println(); // 输出一维数组后换行
}
}
}

2.使用foreach 遍历三维数组
public class ForEachRansack {
public static void main(String[] args) {
int array[][][] = new int[][][]{ // 创建并初始化数组
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } },
{ { 13, 14, 15 }, { 16, 17, 18 } }
};
for (int[][] is : array) { // 遍历数组
for (int[] is2 : is) {
for (int i : is2) {
System.out.print(i + "\t");
}
System.out.println(); // 输出一维数组后换行
}
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-28
Scanner reader=new Scanner(System.in);
int Input=reader.nextInt();
for(int n=1;n<=Input;n++){
vertices[n-1]= "C"+n.toString(); //改成这个试试 //带权有向图的顶点集合
}追问

也是不对的,好像是数组下标溢出,但是我从n-1,n,n+1都试过了,还是不行啊

追答

String vertices[] = new String[10];
Scanner reader=new Scanner(System.in);
int Input=reader.nextInt();
for(int n=1;n<=Input;n++){
Integer n1 = new Integer(n);
vertices[n-1]= "C"+n1.toString(); //改成这个试试 //带权有向图的顶点集合

追问

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

追答

Input你输入时没超过10吧?

追问

是小于100的数

追答

你开辟的数组就10,怎么能小于100都行??

import java.util.Scanner;

public class javaproject {
public static void main(String args[])
{
String vertices[] = new String[100];//你要想让100以内的数都没错,这边要开辟100
System.out.print("qqqqqq");
Scanner reader=new Scanner(System.in);
int Input=reader.nextInt();
for(int n=1;n<=Input;n++){
Integer n1 = new Integer(n); // Integer类才有toString这个函数
vertices[n-1]= "C"+n1.toString();
System.out.print(vertices[n-1]); // 输出就对了~
}

}
}

本回答被提问者采纳
第2个回答  2011-07-05
循环内代码由
vertices[n-1]= "C"+"n.toString()";
改为:
DecimalFormat df=new DecimalFormat("00");
vertices[n-1]= "C"+df.format(n);
第3个回答  2011-07-08
你的for循环从n=1开始,数组下标是从0开始,所以你的n-1没错,但是n<=input这里就错了,这里的n只能小于input 等于input的话下标就越界了、
第4个回答  2011-07-13
刚刚做出来,我运行没问题
package javaSE_bankSystem;
import java.util.*;
public class Test2 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入数字:");
int number = input.nextInt();

String[] vertices = new String[number];
for(int i=0;i<number;i++){
if(i<9){
vertices[i]= "C0"+(i+1);
}else{
vertices[i]= "C"+(i+1);
}
System.out.println(vertices[i]);
}
}
}
相似回答