Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on a game that selects a random word and the user have to find it in less than 7 mistakes, if he makes 7 mistakes he loses, if he makes less than 7 mistakes another word is given and his mistakes are kept. in the end the score is given.
I have a txt file dictionnary, and I wan't to know how to select a word from it and put it in a variable, then show this word hidden in stars * in a JLabel
thank you
What #HotLicks means is to use the Random class or Math.random(), both of which can create a random number. Let say you want to create random number between 0 and 99 inclisive. You would do something like this
Random random = new Random();
int randIndex random.nextInt(100);
What the above does is give you a random index. We will use this random index to select a word.
No to actually get the set of words, you need to get them into some kind of data structure, so you don't have to keep reading the file over and over. Let's say your file looks like this, every word on its own line
Abba
Zabba
Youre
My
Only
Friend
What you want to do is store those words into a data structure like a List. To that you need to read the file line by line, while adding each line to the List
List<String> wordList = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String line;
while((line = br.readLine().trim()) != null) {
wordList.add(line);
}
} catch (IOException ex){
ex.printStackTrace();
}
Now the wordList has all the words from your file. And the randIndex variable holds a random index from the list. So you could do
String randWord = wordList.get(randIndex);
Of course though in the vary first piece of code in the this answer, you need to know the size of the list, before you can decide what number the random number should do up to. So after you populate the list, you would do something like this
Random random = new Random();
int randIndex = random.netInt(wordList.size());
So every time you need a new word, just generate a new random number and use that numbers to get a word from the list at that index.
Please see Basic I/O trail for more help with reading files.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
So I am making a program that can add, edit and delete records from a 2d array.
What I have done to add an array is to collect input from the user by Scanner, and then turn it into an array, and then use java.utils.Arrays to make a copy of the array and then overwrite the original array
This is done through the code below:
static String[][] AssManager = {
{"Natasha Binti Iman Raman", "natasha.raman#taylors.edu.my", "0123659546", "nat123"},
{"Navid Ali Khan", "navidali.khan#taylors.edu.my", "0114665985", "navid123"},
{"Tan Zheng Shen", "zhengshen.tan#taylors.edu.my", "0165846598", "dex123"},
{"Teh Wei Shen", "weishen.tay#taylors.edu.my", "0161254925", "wei123"}
};
Scanner inp = new Scanner(System.in);
String[] role = {
"",
"",
"",
""
};
System.out.println("Please enter the name.");
role[0] = inp.nextLine();
System.out.println("Please enter the email");
role[1] = inp.nextLine();
System.out.println("Please enter the phone number");
role [2] = inp.nextLine();
System.out.println("Please enter the password");
role[3] = inp.nextLine();
AssManager = Arrays.copyOf(AssManager, AssManager.length + 1);
AssManager[AssManager.length-1] = role;
As for editing and deleting, I pinpoint the the array to be deleted using by collecting input from the user, and then checking whether the particular row actually exists. If it doesn't exist, then it will print out a statement. If it exists, it will then allow me to modify or delete the particular row.
The difficulty that I am facing is that while checking for the rows, it only recognizes the dummy data that already exists, but not the newly made rows.
This is the code used to check whether the row exists::
boolean existing = false;
for (int i = 0 ; i < AssManager.length - 1; i++) {
if (name.equals(AssManager[i][0])){
existing = true;
}
Any row that I made through the program is ignored and I am given the statement that the specific row does not exist.
I have tried to make more copies of the same array while using java.util.Arrays but to no avail. I have also tried searching up my problem elsewhere but I cannot find any solutions that may help me.
I appreciate any sort of advice.
Is there a specific reason you're using a two dimensional array? It makes things unnecessarily complex.
I'd suggest you use an ArrayList. This makes adding, removing and even replacing a lot easier.
Additionally, you should create some kind of entity for the name, email, phone number and password information.
My task is to re-alphabetize a dictionary using 5 different sorting algorithms. I have the algorithms taken care of. The thing I am having trouble with is being able to read a string of text from a file and stop where the definition of the word ends without moving onto the next entry. This means I need each index of my array to be a word and its definition like so:
a[i] = "coronet: n. inferior crown denoting, according to its form, various degrees of noble rank less than sovereign.";
Where it is taken from a list arranged like so:
//Begin list
"orthogonal: adj. having or determined by right angles.
deviate: v. to take a different course.
coronet: n. inferior crown denoting, according to its form, various degrees of noble rank less than sovereign.
incite: v. to rouse to a particular action.
deface: v. to mar or disfigure the face or external surface of."
//End list
From there I can actually sort this array, but I'm currently having trouble using Scanner to properly distinguish where each definition ends.
I have no code for anybody to improve, I just need a method of solving this problem.
Any suggestions are appreciated!
Correct me if I'm wrong, but according to your example, each definition begins with a new line. In that case you can use this code to read one line at a time.
ArrayList<String> defs = new ArrayList<String>();
Scanner sc = new Scanner(new File(*path*));
while(sc.hasNextLine()){
defs.add(sc.nextLine());
}
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).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to multiply numbers from a text file using JAVA but have no idea how.
4
12 4
16 8
14 1
12 8
The first number on the first line represents how many people there are within the document (line 2 "12 4" being the first person "12 8" being the last.)
4 (number of employees)
32 (hours employees have worked) 8 (wage per hour)
38 6
38 6
16 7
I'm trying to find how Java can skip line 1, read line two and multiply the two numbers and then do the same for the other lines.
Please can anyone explain how I could do this?
Cheers!
Here are all the things you need:
To read a file: Java: How to read a text file
To cast to integer: How to convert a String to an int in Java?
To multiply: use * operator
The assumption is that you have been given this as an assignment for homework and either you have not paid attention in class. The key to learning programming, is breaking the task down into manageable tasks.
In your case, write a program to read the input file and echo the output. Once you have that, you are part of the way there.
Next, put the numbers into integer variables. This will involve casting.
Then perform that math and spit out the output.
By performing small tasks, the problem becomes much easier.
I don't really understand your criteria unfortunately, but you seem to be able to understand the formula, and that's all you need. I recommend BufferedReader and FileReader to get the text from the file. From there, it's a good idea to start parsing your Strings around the spaces (there's a method for that), and you can then convert them to integers. Hopefully this puts you on the right track.
You definately need to read upon programming as a whole at first, because this should be one of the basic questions you should be able to answer.
I can give you a rough sketch on how to do it:
Construct a File object out of the place where the 'document' resides.
Read the input, definetely for novices, I would recommend using the Scanner class.
Read the first Integer or Line, save this number.
Read the following pair of Integers or Lines.
Multiply the read numbers.
Output the multiplication result.
You also might want to check some other concerns:
Should your program break on wrong input?
Should your program continue on wrong input?
You should take those things in consideration when reading either the Integers or the Lines out of the document.
I see you are having problems with BufferedReader. So to avoid the overhead of type conversion, you may consider using Scanner.
In your case,
Scanner scanner = new Scanner ("Path to your file with backslash characters escaped");
int myNumber = scanner.nextInt();
It will directly assign the number from the file to your variable.
Create a scanner to read the file
Skip the first line
Iterate over all the numbers
Multiply number pairs
Do something with those numbers
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
// 1. Create a scanner to read the file
Scanner file = new Scanner(new File("textfile.txt"));
// 2. Skip the first line
file.nextLine();
// 3. Iterate over all the numbers
while(file.hasNextInt()) {
int hours = file.nextInt();
int wagePerHour = file.nextInt();
// 4. Multiply number pairs
int totalWage = hours * wagePerHour;
// 5. Do something with those numbers
<do something with the numbers>
}
}
}
This will skip the first line and print out the multiplied values for every following line. This is assuming that you are passing a file as a command-line argument.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Multiply{
public static void main(String[] args) throws FileNotFoundException{
File file = new File(args[0]);
Scanner sc = new Scanner(file);
// skip the first line
sc.nextLine();
int num_people;
int hours;
int total;
while(sc.hasNext()){
num_people = sc.nextInt();
hours = sc.nextInt();
total = num_people * hours;
System.out.println(total);
}
}
}
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.