This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 years ago.
Im making a program to take the user input which stands for how many numbers they want, and i have to show as many random numbers as they say. heres the little part i have so far:
if(selection==3)
{
System.out.print("How many numbers would you like to see?");
int ran=kb.nextInt();
}
(theres more code but i just cant figure out how to di this part. any help? thank you :)
I am not sure if I understood your question correctly,
If you are looking to generate a random number within the range of
0-n where n being the input, then try random.nextInt(n)
If you are looking to generate n number of random numbers, where n
being the input, then Write a simple for loop to generate n number of
random numbers.
Check out the Commons Math lib. There are a lot of nice methods in there to just reuse and be done with it.
I don't know what kb is, but you'll need to get the user's input from System.in. It will be a string. You'll want to do something like this (assuming you've put the user's input in a String variable called userInput):
try {
int ran = new Random().nextInt(Integer.parseInt(userInput.trim()));
} catch (NumberFormatException e) {
//handle non-number input here
}
Java's built-in Random number generator will get you your random numbers. What this does is trim any space characters off the input string and then parse it into an integer. You'll need to handle the case that the input is bad in the exception handler.
Related
I want my program to check if the item entered is already in arrayList which is stored within my file ChessList.java, if so produce error and loop back to question else accept number and move on.
Reason being I only want one number to be selected in a row.
Say my program asks for Piece 1, row number and USER ENTERS 5
Then when program loops to piece 2, row number cannot accept 5 again and would produce error.
Therefore, two pieces cannot be contained within in the same row.
Any suggestions how I would go about this? thanks.
I haven't read your code because there's a lot of it, but it just sounds like you want something like
while(true){
int number = getNumber();
if(list.contains(number){
System.out.println("That number is already in the list. Try again");
else{
list.add(number);
break;
}
}
An alternative would be to store it as a Set, which does not store duplicates.
I am trying to write a program containing 3 String ArrayLists, where 1 item may be included in all 3 ArrayLists. However, the output must insure that the randomly selected items are all different. As I work through this issue, I am just using numbers so it will be easier to catch. I have been trying to solve this problem for a few days now, and figure there must be something I am overlooking. Here is the code for the method that must have the fault:
private void generateThree() {
// Find the maximum number the random can be.
index = thirdNumberArray.size();
// Initiate the random function.
Random rand = new Random();
// Generate a random number from 1 to the maximum.
randomInt = rand.nextInt(index);
// Access the item in the ArrayList using the random number as the index.
thirdDrawn = thirdNumberArray.get(randomInt);
// Check that the number is different than any previously set numbers.
while ((thirdDrawn.equals(secondDrawn)) || (thirdDrawn.equals(firstDrawn))) {
randomInt = rand.nextInt(index);
thirdDrawn = thirdNumberArray.get(randomInt);
}
// Set the output.
thirdNumberLabel.setText((thirdDrawn));
// Reset the index.
index = 0;
}
So far, the IF statement I use to check the secondDrawn against the firstDrawn has worked perfectly. But the above code still allows the thirdDrawn to display a duplicate of both the firstDrawn and secondDrawn. I know this problem has to be in my loop logic, but I just can't grasp what it is. I have tried multiple different IF statements, but they didn't solve the whole problem. Can anyone give me some feedback or corrections? Thanks in advance.
Any time you generate a number you want to draw, add it to a HashSet<String>. Then, have your if statement conditional check !myHashset.contains(thirdDrawn).
I'm just learning Java and am practicing creating methods and then invoking them in my main program. To practice this I created a simple program that's supposed to gather data from a prospective horse rider.
Here is the main application:
public class CompleteApp {
public static void main(String[] args) {
TaskOne weight1 = new TaskOne();
TaskTwo nameagehealth1 = new TaskTwo();
TaskThree phoneaddress1 = new TaskThree();
if (weight1.Weight() < 250) {
nameagehealth1.NameAgeHealth();
phoneaddress1.AddressPhone();
}
else {
System.out.println("Thanks for checking!");
}
}
}
I've created three separate classes to do different tasks. Here is the class that's having prompting the error:
import java.util.Scanner;
public class TaskThree {
static void AddressPhone() {
Scanner input = new Scanner(System.in);
System.out.println("Please tell me your address: ");
String address = input.nextLine();
System.out.println("Please tell me your phone number: ");
int phone = input.nextInt();
System.out.println("You said your address is " + address + " and your phone is " + phone + ".");
System.out.println("Thank you for the information, we'll be in touch soon to schedule your ride.");
}
}
The error:
Exception in thread "main" java.util.InputMismatchException: For input string: "3037201234"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at TaskThree.AddressPhone(TaskThree.java:10)
at CompleteApp.main(CompleteApp.java:13)
It seems to indicate that the error is in the phone number and that is being read as a String, yet I made it an integer. I'm not sure where I'm going wrong here. Also, how would I handle it if a user entered their phone number like this: 303-720-1234 vs 3037201234?
Thanks so much for the help!
Since it can't be stored as an int due to the length as Sibbo mentioned, and you're concerned about formatting then you should store it as a String. If you have to do any type of checking to make sure the user inputs data in the correct format (either 1234567890 or 123-456-7890) then you should look into regular expressions. If you run a regular expression on your string then you will be able to get a boolean result to tell you whether or not it is valid.
Why not represent the phone number as a String and use scanner.next()? As mentioned before, when a phonenumber start with a 0 this zero would be removed if you use anything other than String, so I think it's the best way to go.
From your comments, I read that parsing it to a Long works for you. I would strongly recommend using a String though, for several reasons:
Phone numbers with leading zeroes (like international phone numbers). Integers and Longs 'trim' leading zeroes, rendering your phone numbers useless.
If you want to do some extra stuff when presenting your phone numbers (like adding dashes or anything), you will have to parse your Integer/Long back to a String and do your representation magic anyway.
As you just found out, not every phone number can be stored in a 32-bit Integer, but you already worked around that using a Long.
There are probably more reasons for this, but these 2 come to mind.
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). Your input value is out of the range of int.
You should store phone number as String rather than int. If you want to handle numbers like 303-720-1234, parse it as string, remove the - character and then use it.
The input 3037201234 is too large to be represented as an int, so it cannot be parsed as an int.
Integers in Java range from −2,147,483,648 to 2,147,483,647.
Instead of using int for variable phone declare it as long and instead of input.nextInt() use method input.nextLong(). I think this will solve your problem.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Integer with leading zeroes
The program I am coding requires me to label an item with an inventory number of 012345 and store it in a int variable.
This is a stripped down example of what I am doing:
int test = 012345;
System.out.println(test);
this prints as:
5349
How do I get it to print out as 012345 rather than 5349?
EDIT: I am entering this into the parameter of a constructor for a custom class i am initializing. Then I use a method to return what the current number is, then print it to the terminal window.
You get a wrong number because when you prepend zero to an integer literal, Java interprets the number as an octal (i.e. base-8) constant. If you want to add a leading zero, use
int test = 12345;
System.out.println("0"+test);
You can also use the formated output functionality with the %06d specifier, like this:
System.out.format("%06d", num);
6 means "use six digits"; '0' means "pad with zeros if necessary".
As already said, int value with leading zero is considered as octal value. If you don't need to have test as int, why not make it string? Like
String test= new String("012345");
And if you want to use int for test, you can do not prepend 0, rather just use the number and prepend 0 at the time of printing.
In case if you're wondering how will you find how many leading zero are to be prepended, you may do like this
int lengthOfItemID=6;
int test=12345;
String test1=new String("000000"+test);
System.out.println(test1.substring(test1.length()-lengthOfItemID));
Pardon syntax mistakes, been years I last worked with java.
You can get the right result by using Integer.parseInt. That will make your string into a decimal string. (found here). The JAVA API here states that it takes a string and returns a signed decimal.
I'm a beginner in Java, and NetBeans. I'm trying to make a simple program where you introduce 2 numbers and their sum gets divided by two. However, I'm using JFormattedTExtFields and I don't know how to customize the allowed input in them. Basically I'm trying to find out how to:
Only allow numbers to be entered in JFormmatedTextField;
Only allow a certain amount of numbers;
You could use a NumberFormat and specify the maximum number of integer digits with setMaximumIntegerDigits.
Here's a nice article.
Basically you can do something like:
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumIntegerDigits(maxDigitsAmount);
JFormattedTextField field = new JFormattedTextField(f);
The Format should guarantee that the inserted String satisfy the format. Anyway even if a number is supplied, the textfield will store it as a String. So if you need your original Integer you need to rebuild it like suggested #noise:
Integer i = Integer.toString(field.getText());