This question already has answers here:
How to read a specific line using the specific line number from a file in Java?
(19 answers)
Closed 3 years ago.
Im a novice java learner, i have a little problem and i hope you guys can help me out.
i have a Names.txt file that contains a huge amount of random names, each line has an appropriate name
(expl:
jhon
Micheal
Anthony
etc...)
I've been writing a function that randomly choses one of these names:
public static void RandomNameGenerator() throws FileNotFoundException
{
// the File.txt has organized names, meaning that each line contains a name
//the idea here is to get a random int take that number and find a name corresponding to that line number
int txtnumlines = 0; // how many lines the txt file has
Random random = new Random();
Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
while (file.hasNext()) //counts the number of lines
{
file.nextLine();
txtnumlines += 1;
}
int randomintname = random.nextInt(txtnumlines);
// takes a random number, that number will be used to get the name from the txt line
String RandomName = "";
// I'm stuck here :(
}
the problem is i don't know how to continue, more specifically how to extract that name (let's say alex) using the random integers i have that represents a random line
hope my question was clear,
Thank you for helping me out!
Here, you might want to try this:
public static void RandomNameGenerator() throws FileNotFoundException
{
// the File.txt has organized names, meaning that each line contains a name
//the idea here is to get a random int take that number and find a name corresponding to that line number
int txtnumlines = 0; // how many lines the txt file has
Random random = new Random();
Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
Scanner fileReloaded = new Scanner(new File("Names.txt")); //Let's use another one since we can't reset the first scanner once the lines have been counted (I'm not sure tho)
while (file.hasNext()) //counts the number of lines
{
file.nextLine();
txtnumlines += 1;
}
int randomintname = random.nextInt(txtnumlines);
// takes a random number, that number will be used to get the name from the txt line
int i = 0;
String RandomName = "";
while(fileReloaded.hasNext())
{
String aLine = fileReloaded.nextLine();
if (i == randomintname) Randomname = aLine;
i++;
}
// Now you can do whatever you want with the Randomname variable. You might want to lowercase the first letter, however. :p
}
Reading all lines
String[] lines = new Scanner(
MyClass.class.getClassLoader().getResourceAsStream("Names.txt"),
StandardCharsets.UTF_8.name()
).next().split("\\A");
Extract random line
Random random = new Random();
String randomLine = lines[random.nextInt(lines.length)].trim();
Related
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 months ago.
I am currently learning Java and received the following task, that I cannot seem to solve:
"Create a Java program that prints one random poem of 5 lines in the console. The poems must be read from a text file."
I have copied 10 different poems inside a text file, all written underneath each other. I managed to make the program print out the very first poem (first 5 lines) in the console, but first of all, I am not sure if it's the correct way to do such, and I don't know how to make the program print out one random poem (5 lines that belong together) each time I run it.
Here is the farthest I could get:
public static void main(String[] args) throws IOException {
File file = new File("src/main/java/org/example/text.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
int i = 0;
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (i < 5) {
i++;
System.out.println(line);
}
}
} catch (Exception e) {
}
}
You can try
private static final int POEM_LINES_LENGTH = 5;
public static void main(String[] args) throws IOException
{
// The file
File file = new File("src/main/java/org/example/text.txt");
// Get all the lines into a single list
List<String> lines = Files.readAllLines(Paths.get(file.getAbsolutePath()));
// Get a random poem and point at the end.
int poemFinish = new Random().nextInt(lines.size() / POEM_LINES_LENGTH) * POEM_LINES_LENGTH;
// Point to the be start
int start = poemFinish - POEM_LINES_LENGTH;
// Create a sublist with the start and finish indexes.
for (String line : lines.subList(start, poemFinish))
System.out.println(line);
}
This will not read the entire file into the memory, hence large files can also be read.
final int totalPoems = 17;
int skip = new Random().nextInt(totalPoems) * 5;
Path path = Paths.get("file.txt");
BufferedReader reader = Files.newBufferedReader(path);
while(skip-->0){
reader.readLine();
}
for(int i=0; i<5; i++){
System.out.println(reader.readLine());
}
The downside is you have to know how many poems are in the file beforehand. If you don't want to do this you can quickly count the total number of lines/poems only one time.
So I am having trouble reading in a file. The file contains 2 integers in the first line, and the rest of the file contains Strings in seperate lines. For some reason my logic in this code, it does not seem to consume each line in the file correctly. I tried to troubleshoot this by printing out what was happening, and it seems like the second nextLine() is not even executing.
while(inputFile.hasNext())
{
try
{
String start = inputFile.nextLine();
System.out.println(start); // tried to troubleshoot here
String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
System.out.println(rowsAndCols[0]); // tried to troubleshoot here
int rows = Integer.parseInt(rowsAndCols[0]);
int cols = Integer.parseInt(rowsAndCols[1]);
cell = new MazeCell.CellType[rows+2][cols+2];
String mazeStart = inputFile.nextLine(); // part where it should begin to read the rest of the file containing strings
String [] mazeRowsAndCols = mazeStart.split(" ");
MazeCell.CellType cell2Add;
Based upon your description above, only the first line contains Integers, so your while loop is wrong as it is trying to convert every line into Integers.
Split into the code into
if (inputFile.hasNextLine())
{
String start = inputFile.nextLine();
String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
int rows = Integer.parseInt(rowsAndCols[0]);
int cols = Integer.parseInt(rowsAndCols[1]);
}
then a while loop for the String reading
I working on a project that is based on reading a text from a file and putting it as objects in my code.
My file has the following elements:
(ignore the bullet points)
4
Christmas Party
20
Valentine
12
Easter
5
Halloween
8
The first line declares how many "parties" I have in my text file (its 4 btw)
Every party has two lines - the first line is the name and the second one is the number of places available.
So for example, Christmas Party has 20 places available
Here's my code for saving the information from the file as objects.
public class Parties
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{
Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt"));
int first = inFile.nextInt();
inFile.nextLine();
for(int i=0; i < first ; i++)
{
String str = inFile.nextLine();
String[] e = str.split("\\n");
String name = e[0];
int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand
Party newParty = new Party(name, tickets);
System.out.println(name+ " " + tickets);
}
This is my SingleParty Class:
public class SingleParty
{
private String name;
private int tickets;
public Party(String newName, int newTickets)
{
newName = name;
newTickets = tickets;
}
Can someone explain to me how could I approach this error?
Thank you
str only contains the party name and splitting it won't work, as it won't have '\n' there.
It should be like this within the loop:
String name = inFile.nextLine();
int tickets = inFile.nextInt();
Party party = new Party(name, tickets);
// Print it here.
inFile().nextLine(); // for flushing
You could create a HashMap and put all the options into that during your iteration.
HashMap<String, Integer> hmap = new HashMap<>();
while (sc.hasNext()) {
String name = sc.nextLine();
int tickets = Integer.parseInt(sc.nextLine());
hmap.put(name, tickets);
}
You can now do what you need with each entry in the HashMap.
Note: this assumes you've done something with the first line of the text file, the 4 in your example.
nextLine() returns a single string.
Consider the first iteration, for example, "Christmas Party".
If you split this string by \n all you're gonna get is "Christmas Party" in an array of length 1. Split by "blank space" and it should work.
I have a .txt file that lists integers in groups like so:
20,15,10,1,2
7,8,9,22,23
11,12,13,9,14
and I want to read in one of those groups randomly and store the integers of that group into an array. How would I go about doing this? Every group has one line of five integers seperated by commas. The only way I could think of doing this is by incrementing a variable in a while loop that would give me the number of lines and then somehow read from one of those lines that is chosen randomly, but I'm not sure how it would read from only one of those lines randomly. Here's the code that I could come up with to sort of explain what I'm thinking:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
while (filescan.hasNextLine())
{
line++;
}
Random r = new Random(line);
Now what do I do to make it scan line r and place all of the integers read on line r into a 1-d array?
There is an old answer in StackOverflow about choosing a line randomly. By using the choose() method you can randomly get any line. I take no credit of the answer. If you like my answer upvote the original answer.
String[] numberLine = choose(new File("Coords.txt")).split(",");
int[] numbers = new int[5];
for(int i = 0; i < 5; i++)
numbers[i] = Integer.parseInt(numberLine[i]);
I'm assuming you know how to parse the line and get the integers out (Integer.parseInt, perhaps with a regular expression). If you're sing a scanner, you can specify that in your constructor.
Keep the contents of each line, and use that:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
List<String> content = new ArrayList<String>(); // new
while (filescan.hasNextLine())
{
content.add(filescan.next()); // new
line++;
}
Random r = new Random(line);
String numbers = content.get(r.nextInt(content.size()); // new
// Get numbers out of "numbers"
Read lines one by one from the file, store them in a list and generate a random number from the list's size and use it to get the random line.
public static void main(String[] args) throws Exception {
List<String> aList = new ArrayList<String>();
Scanner filescan = new Scanner(new File("Coords.txt"));
while (filescan.hasNextLine()) {
String nxtLn = filescan.nextLine();
//there can be empty lines in your file, ignore them
if (!nxtLn.isEmpty()) {
//add lines to the list
aList.add(nxtLn);
}
}
System.out.println();
Random r = new Random();
int randomIndex=r.nextInt(aList.size());
//get the random line
String line=aList.get(randomIndex);
//make 1 d array
//...
}
Hi I'm in a programming class over the summer and am required to create a program that reads input from a file. The input file includes DNA sequences ATCGAGG etc and the first line in the file states how many pairs of sequences need to be compared. The rest are pairs of sequences. In class we use the Scanner method to input lines from a file, (I read about bufferedReader but we have not covered it in class so not to familiar with it) but am lost on how to write the code on how to compare two lines from the Scanner method simultaneously.
My attempt:
public static void main (String [] args) throws IOException
{
File inFile = new File ("dna.txt");
Scanner sc = new Scanner (inFile);
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
comparison(DNA1,DNA2);
}
sc.close();
}
Where the comparison method would take a pair of sequences and output if they had common any common characters. Also how would I proceed to input the next pair, any insight would be helpful.. Just stumped and google confused me even further. Thanks!
EDIT:
Here's the sample input
7
atgcatgcatgc
AtgcgAtgc
GGcaAtt
ggcaatt
GcT
gatt
aaaaaGTCAcccctccccc
GTCAaaaaccccgccccc
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gctagtacACCT
gctattacGcct
First why you are doing:
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
While you have pairs only in one line not pairs and two lines of input, but number of lines once? Move reading pairs from that while looop and parse it to int, then it does not matter but you could use it to stop reading lines if you know how many lines are there.
Second:
throws IOException
Might be irrelevant but, really you don't know how to do try catch and let's say skip if you do not care about exceptions?
Comparision, if you read strings then string has method "equals" with which you can compare two strings.
Google will not help you with those problems, you just don't know it all, but if you want to know then search for basic stuff like type in google "string comparision java" and do not think that you can find solution typing "Reading two lines from an input file using Scanner" into google, you have to go step by step and cut problem into smaller pieces, that is the way software devs are doing it.
Ok I have progz that somehow wokrked for me, just finds the lines that have something and then prints them out even if I have part, so it is brute force which is ok for such thing:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program
{
public static void main (String [] args) throws IOException
{
File inFile = new File ("c:\\dna.txt");
Scanner sc = new Scanner (inFile);
int pairs = Integer.parseInt(sc.nextLine());
for (int i = 0; i< pairs-1; i++)
{
//ok we have 7 pairs so we do not compare everything that is one under another
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
Boolean compareResult = comparison(DNA1,DNA2);
if (compareResult){
System.out.println("found the match in:" + DNA1 + " and " + DNA2) ;
}
}
sc.close();
}
public static Boolean comparison(String dna1, String dna2){
Boolean contains = false;
for (int i = 0; i< dna1.length(); i++)
{
if (dna2.contains(dna1.subSequence(0, i)))
{
contains = true;
break;
}
if (dna2.contains(dna1.subSequence(dna1.length()-i,dna1.length()-1 )))
{
contains = true;
break;
}
}
return contains;
}
}