数组未正确显示

时间:2015-11-22 01:20:31

标签: java arrays

当我运行程序时,它会打印索引中的数字,而不是打印出单词。该计划的想法是创建随机句子,任何人都知道我在这里做错了什么?

 public class TestShoutBox5 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
      String Subjects[] = new String[]{"My Teacher","I","You"
   };

   Random RandomSubject=new Random();
   int S = RandomSubject.nextInt(4);

     String Objects[] = new String[]{"Homework", "Work","Quiz"
   };

   Random Randomobjects=new Random();
   int O = Randomobjects.nextInt(4);

 String Verbs[] = new String[]{"Studying", "Playing","Working"
   };

   Random Randomverbs=new Random();
   int R = Randomverbs.nextInt(4);

    String Adjectives[] = new String[]{"Smart", "Tall","Hard"
   };

   Random RandomAdjectives=new Random();
   int A = RandomAdjectives.nextInt(4);

    String Adverbs[] = new String[]{"quickly", "everywhere","fast"
   };

   Random RandomAdverb=new Random();
   int Ad = RandomAdverb.nextInt(4);



 System.out.print("Your Sentence"+S+O+R+A+Ad);

}

}

2 个答案:

答案 0 :(得分:2)

问题在于您要打印索引而不是数组中软管索引处的单词。 而不是:

System.out.print("Your Sentence"+S+O+R+A+Ad);

这样做:

System.out.print("Your Sentence"+ Subjects[S]+Objects[O]+Verbs[R]+Adjectives[A]+Adverbs[Ad]);

修改(来自@ kyriacos_k')

当数组索引从0变为数组的长度-1时,Random对象应该创建0 - 2而不是0 - 3的值。要解决此问题,请使用.nextInt(3)而不是{{ 1}}

答案 1 :(得分:2)

您正在打印密钥,您希望该单元格中的数组内容如此:

C

enter image description here

你也可以用1 随机

来做到这一点
int a[]=new int[5];//declaration and instantiation  
a[0]=10;//initialization  
a[1]=20;  
a[2]=70;  
a[3]=40;  
a[4]=50;  

//printing array  
for(int i=0;i<a.length;i++)//length is the property of array  
 System.out.println(a[i]);   
}}