Java 数组显示不正确
当我运行程序时,它会打印出索引中的数字,而不是打印出单词。这个程序的想法是创造随机的句子,有人知道我做错了什么吗Java 数组显示不正确,java,arrays,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 S
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);
}
}
问题是您打印的是索引,而不是数组中索引处的单词。 而不是:
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时,随机对象应该从0-2而不是0-3创建值。要解决此问题,请使用
.nextInt(3)
而不是.nextInt(4)
问题是您打印的是索引,而不是数组中软管索引处的单词。
而不是:
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时,随机对象应该从0-2而不是0-3创建值。要解决此问题,请使用
.nextInt(3)
而不是.nextInt(4)
如果要打印密钥,则需要该单元格中的数组内容,以便:
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]);
}}
如果要打印密钥,则需要该单元格中的数组内容,以便:
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]);
}}
要打印出数组中的字符串,您需要访问数组位置:例如:
副词[S]
,而不是打印出S
,后者是一个int
JavaScript与此问题无关。请删除标记。要打印出数组中的字符串,您需要访问数组位置:例如:副词[S]
,而不是打印出S
,这是一个int
JavaScript与此问题无关。请删除标记。请说明random.nextInt(4)
应变成random.nextInt(3)
请说明random.nextInt(4)
应变成random.nextInt(3)
应变成random.nextInt(3)
@Bimde random.nextInt(n)从0开始(包含)到n(独占)所以。nextInt(3)会给出0-2的值,这是他想要的。请注意random。nextInt(4)
应该变成random。nextInt(3)
@Bimde random。nextInt(n)是从0(包含)到n(独占)所以。nextInt(3)会给出0-2的值,这是他想要的。