2 Replies - 487 Views - Last Post: 11 March 2012 - 12:08 AM Rate Topic: -----

#1 blackjnr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-March 11

Print 3 numbers randomly inputed by user

Posted 10 March 2012 - 11:51 PM

Hi.
I'm sort of new to java. I'm doing an assignment and part of it is about making a password from a user input. I've written the following code to test if what i'm doing is correct. The user inputs their DOB (eg. 09101990), and three numbers are supposed to be printed from the input randomly. The password does print, but sometimes it prints 1 number, sometimes 5 etc.
How do i get it to print 3 numbers?

import java.util.*;
public class Password
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);

		String DOB;
		System.out.println("enter DOB: ");
		DOB = input.nextLine();
		
		Random generator = new Random();		
		
		int length = DOB.length();
		int index = generator.nextInt(length);
		int numChar = generator.nextInt(length-index) +1;
		int endIndex = index + numChar;
			
		System.out.println("password: " + DOB.substring(index, endIndex));

	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Print 3 numbers randomly inputed by user

#2 jdavi134  Icon User is offline

  • D.I.C Head

Reputation: 42
  • View blog
  • Posts: 225
  • Joined: 26-October 11

Re: Print 3 numbers randomly inputed by user

Posted 10 March 2012 - 11:59 PM

Well, if your using a random number generator, then of course the numbers will never be the same. Random means different every time doesn't it?

Jack
Was This Post Helpful? 0
  • +
  • -

#3 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7877
  • View blog
  • Posts: 13,369
  • Joined: 19-March 11

Re: Print 3 numbers randomly inputed by user

Posted 11 March 2012 - 12:08 AM

Quote

The password does print, but sometimes it prints 1 number, sometimes 5 etc.

		int length = DOB.length();
		int index = generator.nextInt(length);
		int numChar = generator.nextInt(length-index) +1;
		int endIndex = index + numChar;
		System.out.println("password: " + DOB.substring(index, endIndex));



That's exactly the behavior you'd expect from this code.

Imagine that I enter the String "sesquipedalian". Length is 14. I get a random number less than length, say it's 4. Then I get number less than (length-4), and it's 4 again. (4 is a pretty random number). Then I add 1 to it, and add it to index: endIndex is 9. Then I print out a "sesquipedalian".substring(4,9) and the result is "uipe", right?


Quote

How do i get it to print 3 numbers?


Well, if numChar is 3, it'll print three chars from the String. If those are numbers, it'll print three numbers.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1