• Post Reply Bookmark Topic Watch Topic
  • New Topic

Random ()  RSS feed

 
Lesole Mphinyane
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hw do i get do display the following characters in random....

import java.util.*;

public class CharacterArithmetic
{
public static void main(String [] args)
{
char letter = 'A';

for(letter='A'; letter <= 'Z'; letter++)
{
System.out.print(letter + " ");
}
}
}

please help......
 
jeff rusty
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lesole ,

There is no direct method avialable like Math.Random().the Round about way for this is below

char letter[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

for(int i=0;i<letter.length;i++)
{
int character=(int)(Math.random()*26);
System.out.print( letter[character]);
}

This would help you in randomizing the Charachters.This doesnt ensure unique charachters,same charachters may be printed in the loop.If you want the values to be distinct then you have to incoprate a peice of code which would check for already printed ones and also need to change the for loop condition in that case.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could shuffle the array, and then output it in the resulting order.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!