![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
|
Help plz
Hi, I'm new to Java but that's what I'm learning now and I've got a question. My task is to generate a random phone number of format xxx-xxx-xxxx. The first part can not contain 8 or 9, and the second part has to be less than 742, nothing special about the third part. I only have to generate and output it but I want to make it so that the program asks user if he wants to generate another number or not. My question is below the code.
Here's what I came up with //****************************************
// phonenumber.java
// This program generates a random
// phone number of the format xxx-xxx-xxxx
//****************************************
import java.util.Scanner;
import java.util.Random;
public class phonenumber {
public static void main (String[] args) {
int numb1, numb2, numb3, num2, num3, ans;
Random number = new Random();
numb1 = number.nextInt(8);
numb2 = number.nextInt(8);
numb3 = number.nextInt(8);
num2 = number.nextInt(742);
num3 = number.nextInt(10000);
System.out.println ("A random phone number is: " + numb1 + numb2 + numb3 + "-" + num2 + "-" + num3);
Scanner answer = new Scanner(System.in);
System.out.print ("Would you like to generate another phone number? Enter 1 to continue, 0 - to quit: ");
ans = answer.nextInt();
while (ans != 0 && ans == 1)
{
numb1 = number.nextInt(8);
numb2 = number.nextInt(8);
numb3 = number.nextInt(8);
num2 = number.nextInt(742);
num3 = number.nextInt(10000);
System.out.println();
System.out.println ("A random phone number is: " + numb1 + numb2 + numb3 + "-" + num2 + "-" + num3);
System.out.print ("Would you like to generate another phone number? 0/1: ");
ans = answer.nextInt();
}
}
}Where can I insert an if-statement (or if-else) so that if the answer isn't 0 or 1 it will say Something like "Error, try again" and will promt to enter 0 or 1 (I'm not using y/n , because 0 and 1 will do)? I tried but the if-statement is always executed and as a result I get a prompt twice. Any suggestions? Also, if you can help me to find an easier way of writing the code plz tell me. I repeat, I'm only in the beginning of my way in programming . Thanks in advance.
__________________
M.A.C.I.N.T.O.S.H. - Machine Always Crashes, If Not, The Operating System Hangs. |
|
|
|
|
|
#2 |
|
Newbie
|
never mind, I solved it.
Thanks for 29 views at least... ![]()
__________________
M.A.C.I.N.T.O.S.H. - Machine Always Crashes, If Not, The Operating System Hangs. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|