Reading text files into array - arrays

I'm trying to store girl and boy names into an array.
I got most of the code except the storing the files into an array.
This is what girls.txt looks like
Emma 125125
Elaina 415545
Kim 545454
Boys.txt:
Devan 45645
Tom 4545
Chris 4879797
i need help storing the names and numbers from files into array boynames array and girlnames array. I show where i need help with comments in code
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1Names {
public static void main(String[] args) {
Scanner inputStream = null;
String[][] boynames = new String[1000][2];
String[][] girlnames = new String[1000][2];
String line = null;
boolean isFoundB = false;
boolean isFoundG = false;
try {
inputStream = new Scanner(new FileInputStream("boys.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file boys.txt");
System.exit(0);
}
Scanner inputStreamGirls = null;
try {
inputStreamGirls = new Scanner(new FileInputStream("girls.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file girls.txt");
System.exit(0);
}
int count = 0;
while (count < 1000){
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
count++;
}
count = 0;
while (count < 1000 ){
inputStreamGirls = girlnames[count][0]; //here
inputStreamGirls = girlnames[count][1]; //here
count++;
}
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first name that you would like to find the popularity of.\n Be sure to capitalize the first letter of the name.\n");
String answer = keyboard.next();
count = 0;
while(count < 1000){
if (boynames[count][0] == answer){
System.out.println(boynames[count][0] + " is ranked " + count + " among boys with " + boynames[count][1] + " namings");
isFoundB = true;
}
if (girlnames[count][0] == answer){
System.out.println(girlnames[count][0] + " is ranked " + count + " among girls with " + girlnames[count][1] + " namings");
isFoundG = true;
}
count++;
}
if(isFoundB == false){
System.out.println(answer + " is not ranked among the top 1000 boy names.");
}
if(isFoundG == false){
System.out.println(answer + " is not ranked among the top 1000 girl names.");
}
inputStreamGirls.close();
inputStream.close();
keyboard.close();
}
}

You will need to call the scanner methods to actually read from the input file.
scanner.next() reads one string token from the input.
So instead of this part:
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
You would do:
boynames[count][0] = inputStream.next();
boynames[count][1] = inputStream.next();

Related

Displaying Multidimensional Arrays in Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class JavaClass {
public static void main(String[] args) {
// Things start here
int[][] multi = new int[5][10];
for(int p = 1; p < 5; p++)
{
for(int h = 1;h < 10;h++)
{
System.out.println("Enter the score for Player " + String.valueOf(p) + ", Hole " + String.valueOf(h) + " :");
String v = stringReader();
multi[p][h] = Integer.parseInt(v);
System.out.println(String.valueOf(v));
}
}
}
public static String stringReader()
{
String value;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
value = bufferedReader.readLine();
} catch (IOException e) {
value = "0";
}
return value;
}
Hello! I am currently working on a project for my Grade 12 Computer Science course where i am asked to make a "Golf Score Tracker" the description of the project is (add to the code below code that calculates and displays each golfers individual score)
I've tried working with while loops however whatever I do it does not seem to display. My teacher is also stuck lol he is actually the reason I am here asking for help on this project

Optimizing Replacing Bytes of Some File in Java 8

I have this method in Java and I want to improve it.
The method is used to replace some part (at the beginning, in the middle or at the end) of some File with the new bytes (the selected part can be replaced by less or more bytes).
The selection is done, by position(start) and quantity.
I can't to use external libraries (guava, or some other).
Here my old code:
public static void replaceBytesFile(RandomAccessFile rafTarget,
byte[] replacers, int start, int quantity) {
//replaces exact amount of bytes of a file starting at a specified position
RandomAccessFile rafTemp = null;
//Ini Select a Random NonExistent File
File userDirectory = new File(System.getProperty("user.dir"));
File temporalFile;
boolean existsTemporalFile = false;
String temporalFilename = "";
while (!existsTemporalFile) {
temporalFilename = "File_" + Double.toString(100000 * Math.random()) + ".tmp";
temporalFilename = userDirectory + MethodGen.FS + temporalFilename;
temporalFile = new File(temporalFilename);
if (!temporalFile.exists()) {
existsTemporalFile = true;
}
}
//End Select a Random NonExistent File
try {
rafTemp = new RandomAccessFile(temporalFilename, "rw");
int workBufferSize = 65536;
//Ini Copy first (Start - 1) MethodBytes
int step = workBufferSize;
int countPosition = 0;
while (countPosition < start) {
rafTarget.seek(countPosition);
rafTemp.seek(countPosition);
if ((start - countPosition) < step) {
step = start - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
countPosition += step;
}
//End Copy first (start - 1) MethodBytes
rafTemp.write(replacers);
rafTarget.seek(start + quantity);
int end = (int) rafTarget.length();
//Ini Copy last MethodBytes
step = workBufferSize;
countPosition = start + quantity;
while (countPosition < end) {
rafTarget.seek(countPosition);
rafTemp.seek(countPosition - quantity + replacers.length);
if ((end - countPosition) <= step) {
step = end - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
countPosition += step;
}
//End Copy last MethodBytes
rafTarget.setLength(0);
step = workBufferSize;
countPosition = 0;
end = (int) rafTemp.length();
//Ini Copy all MethodBytes to original
while (countPosition < end) {
rafTemp.seek(countPosition);
rafTarget.seek(countPosition);
if ((end - countPosition) <= step) {
step = end - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTemp.read(WorkBuffer);
rafTarget.write(WorkBuffer);
countPosition += step;
}
//End Copy all MethodBytes to original
rafTemp.close();
temporalFile = new File(temporalFilename);
temporalFile.delete();
} catch (IOException ioe) {
System.out.println(ioe.toString());
} finally {
try {
if (rafTemp != null) {
rafTemp.close();
}
} catch (IOException e) {
}
}
}
I'm copying manually in from original file to temporal file where the changes are performed, later ,
My code is working, but I want to know some best alternative in Java 8 (preferred).
Now How is test?
public static void main(String[] args) {
String originalFilename = "OriginalTraveling.txt";
String copiedFilename = "TravelingToBeChanged.txt";
Path copiedPath = Paths.get(copiedFilename);
Path originalPath = new File(originalFilename).toPath();
System.out.println("filename:" + originalFilename);
String contet = "I want to travel to my Country.";
try {
RandomAccessFile raf = new RandomAccessFile(originalFilename, "rw");
putBytesFile(raf, contet.getBytes(), 0);
Files.copy(originalPath, copiedPath, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e) {
System.out.println("Exception caught " + e.toString());
}
try {
RandomAccessFile raf = new RandomAccessFile(copiedFilename, "rw");
String toBeChanged = "my Country.";
String toBeInserted = "India, China, Europe, Latin America, Australia.";
int position = contet.indexOf(toBeChanged);
replaceBytesFile(raf, toBeInserted.getBytes(), position, toBeChanged.length());
}
catch (IOException e) {
System.out.println("Exception caught " + e.toString());
}
try {
RandomAccessFile raf = new RandomAccessFile(copiedFilename, "rw");
String replacedContent = new String(getBytesFile(raf, 0, (int) raf.length()));
String toBeChanged = "Latin America";
String toBeInserted = "Colombia";
int position = replacedContent.indexOf(toBeChanged);
replaceBytesFile(raf, toBeInserted.getBytes(), position, toBeChanged.length());
} catch (IOException e) {
System.out.println("Exception caught " + e.toString());
}
}
Method to put Bytes!
public static void putBytesFile(RandomAccessFile RAFTarget, byte[] content, int position) {
int size = content.length;
try {
long oldPosition = RAFTarget.getFilePointer();
if (!((position < 0) || !(size > 0))) {
RAFTarget.seek(position);
RAFTarget.write(content);
RAFTarget.seek(oldPosition);
}
} catch (java.io.IOException e) {
System.out.println(e.toString());
}
}
Method Get Files!
public static byte[] getBytesFile(RandomAccessFile RAFSource, int position, int quantity) {
byte[] content = null;
try {
long oldPosition = RAFSource.getFilePointer();
if ((position < 0) || !(quantity > 0)) {
return (content);
} else {
if (RAFSource.length() < (position + quantity)) {
quantity = (int) RAFSource.length() - position;
}
RAFSource.seek(position);
content = new byte[quantity];
RAFSource.read(content);
RAFSource.seek(oldPosition);
}
} catch (java.io.IOException e) {
System.out.println(e.toString());
}
return content;
}
Content of OriginalTraveling.txt
I want to travel to my Country.
Content of TravelingToBeChanged.txt
I want to travel to India, China, Europe, Latin America, Australia.
Finally the Content of TravelingToBeChanged.txt
I want to travel to India, China, Europe, Colombia, Australia.
If it can be noticed, they are NOT changed by the same number of bytes.
Do you know some alternative to replace contents of File?
Even for ancient code, this looks unnecessary complicated.
E.g. instead of
//Ini Select a Random NonExistent File
File userDirectory = new File(System.getProperty("user.dir"));
File temporalFile;
boolean existsTemporalFile = false;
String temporalFilename = "";
while (!existsTemporalFile) {
temporalFilename = "File_" + Double.toString(100000 * Math.random()) + ".tmp";
temporalFilename = userDirectory + MethodGen.FS + temporalFilename;
temporalFile = new File(temporalFilename);
if (!temporalFile.exists()) {
existsTemporalFile = true;
}
}
just use
File temporalFile = File.createTempFile("File_", ".tmp", userDirectory);
See createTempFile
Further, instead of
int step = workBufferSize;
int countPosition = 0;
while (countPosition < start) {
rafTarget.seek(countPosition);
rafTemp.seek(countPosition);
if ((start - countPosition) < step) {
step = start - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
countPosition += step;
}
Use
for(int step=workBufferSize, countPosition=0; countPosition < start; countPosition += step){
rafTarget.seek(countPosition);
rafTemp.seek(countPosition);
if ((start - countPosition) < step) {
step = start - countPosition;
}
byte[] WorkBuffer = new byte[step];
rafTarget.read(WorkBuffer);
rafTemp.write(WorkBuffer);
}
As you clearly have an initial statement, a condition and an increment operation, in other words, a typical for loop. The same applies to the other two while loops.
However, with newer APIs, things are much simpler anyway:
// consider using long for position and Path for the file, unless
// the RandomAccessFile is really needed for other purposes
public static void replaceBytesFile(RandomAccessFile rafTarget,
byte[] replacers, int start, int quantity) throws IOException {
// no need to force a particular directory for the temp file
Path tmp = Files.createTempFile("File_", ".tmp");
// use import static java.nio.file.StandardOpenOption.*;
// try( ... ) closes automatically, perfect for a temp file with DELETE_ON_CLOSE
try(FileChannel tmpCh = FileChannel.open(tmp, READ, WRITE, DELETE_ON_CLOSE)) {
// closing the target channel would also close rafTarget RandomAccessFile
FileChannel target = rafTarget.getChannel();
// just keep the data before start position, only copy remainder
long retainStart = start + (long)quantity, toCopy = target.size() - retainStart;
target.transferTo(retainStart, toCopy, tmpCh);
// write the replacement
target.write(ByteBuffer.wrap(replacers), start);
// copy back the remainder, to the new position
tmpCh.position(0);
target.transferFrom(tmpCh, start + (long)replacers.length, toCopy);
// adapt the length if necessary
target.truncate(start + toCopy + replacers.length);
}
}

I have A text file with id no name and grades i want to extract the ID no, and grades then calculate the average and append it to another file

PrintWriter out = new PrintWriter(new FileWriter("students.txt", true));
do
{
//get the info from user to write to file
System.out.print("Enter The Student ID: ");
idNo = keyIn.nextLine();
System.out.print("Enter The Student Name: ");
name = keyIn.nextLine();
System.out.print("Enter The Student Grades: ");
grades = keyIn.nextInt();
keyIn.nextLine(); //clear buffer
out.println(idNo +" " +name +" " +grades); //write line to output file
System.out.print("Do You Have Another Student To Process: ");
response = keyIn.next().charAt(0);
keyIn.nextLine(); //clear buffer
}while(response != 'n');
//close files
out.close();
//in.close();
break;
case 2: // Write Student Test Marks To results.txt
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer >();
while ((line = br.readLine()) != null) {
String temp[]=line.split(" ");
if (map.containsKey(Integer.parseInt(temp[0]))) {
int val=hmap.get[Integer.parseInt(temp[0])];
val+=Integer.parseInt(temp[2]);
map.put(Integer.parseInt(temp[0]),val);
} else {
map.put(Integer.parseInt(temp[0]),Integer.parseInt(temp[2]));
}
}
}
try{
PrintWriter writer = new PrintWriter("results.txt", "UTF-8");
Iterator it = hmap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
writer.println(pair.getKey() + " " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
writer.close();
} catch (IOException e) {
// do something
}

Comma separated string split by length but keeping the comma separation?

I have a string like this "105321,102305,321506,0321561,3215658" and i need to split this string by the comma (,) and with a specific length, so if the length of each string part is 15, the splited array must be like:
105321,102305
321506,0321561
3215658
I try several ways but i can't find the right approach to do this
The code that i have gives me an error of index out of range:
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
for(int i = 0; i < firstSplit.Length; i++)
{
string part = firstSplit[i];
if(output.Any() && output[i].Length + part.Length >= maxSplit)
{
output.Add(part);
}
else
{
if(!output.Any())
output.Add(part);
else
output[i] += "," + part;
}
}
return output;
}
Edit: i must say that the comma , must be a part of the amount of the maxSplit variable.
This one would be concise, yet not really performant
private static Pattern P = Pattern.compile("(.{1,15})(,|$)");
private static String[] split(String string) {
Matcher m = P.matcher(string);
List<String> splits = new ArrayList<String>();
while (m.find()) {
splits.add(m.group(1));
}
return splits.toArray(new String[0]);
}
The regular expression in P matches (.{1,15})(,|$):
a sequence of 1 to 15 characters = .{1,15}
followed by , or line ending
the parentheses allow grouping, the content of the first group is what you are interested in
static void Main(string[] args)
{
string originalString = "105321,102305,321506,0321561,3215658";
string[] commaSplit = originalString.Split(',');
string tempString = string.Empty;
List<string> result = new List<string>();
for (int i = 0; i < commaSplit.Length; i++ )
{
if ((tempString.Length + commaSplit[i].Length) > 15)
{
result.Add(tempString);
tempString = string.Empty;
}
if (tempString.Length > 0)
{
tempString += ',' + commaSplit[i];
}
else
{
tempString += commaSplit[i];
}
if (i == commaSplit.Length - 1 && tempString != string.Empty)
{
result.Add(tempString);
}
}
foreach (var s in result)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
This may not be the best solution but it works ;)
what about this?
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
int i = 0;
while (i < firstSplit.Length)
{
string part = firstSplit[i];
while (part.Length < maxSplit)
{
if (part.Length < maxSplit && i + 1 < firstSplit.Length)
{
if ((part + "," + firstSplit[i + 1]).Length < maxSplit)
{
part += "," + firstSplit[i + 1];
i++;
}
else
{
output.Add(part);
i++;
break;
}
}
else
{
output.Add(part);
i++;
break;
}
}
}
return output;
}

Output from reading a text file is repeating lines when appending in Java?

I've made a simple text box which when a button is pressed loads the text from a text file (line by line). It writes the numbers to a JTextArea then it applies some methods to the numbers and outputs the results into a JTextArea.
My problem is that when the output is shown it repeats the lines - it is easier to show by example.
So if the text file reads:
1
2
The output given is:
First TextArea:
1
2
Second TextArea:
resultFrom1
resultFrom1
resultFrom2
So the numbers are displaying fine but the processed data is repeating itself. In this case it shows the program displaying the first result and then displaying both results.
The code for the load button is:
private void loadPlaylistBtnActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == loadPlaylistBtn) {
try {
playlistTextArea.setText(null);
FileReader fileReader = new FileReader("playlist.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputFile = "";
String textFieldReadable = bufferedReader.readLine();
while (textFieldReadable != null) {
inputFile += textFieldReadable + "\n";
textFieldReadable = bufferedReader.readLine();
trackNum.setText(inputFile);
String[] loadPlaylist = trackNum.getText().split("\\n");
for (int i = 0; i < loadPlaylist.length; ++i) {
String songName = LibraryData.getName(loadPlaylist[i]);
String songArtist = LibraryData.getArtist(loadPlaylist[i]);
playlistTextArea.append(songName + " - " + songArtist + "\n");
}
}
fileReader.close();
} catch (Exception e) {
System.out.println("File not found.");
}
}
}
The methods in LibraryData are:
getName:
public static String getName(String key) {
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM Library WHERE LibraryID = '" +
key + "'");
if (res.next()) {
return res.getString(2);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
and getArtist:
public static String getArtist(String key) {
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM Library WHERE LibraryID = '" + key + "'");
if (res.next()) {
return res.getString(3);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
Any ideas on how I can make it just output one of the songs relating to the number, rather than repeating itself?
Sorry if this has been really unclear - I'm still quite new to Java.
Thanks :)
Using the assumption that playlistTextArea is your problem test box, the problem seems to be:
playlistTextArea.append(songName + " - " + songArtist + "\n");
You're reading the file lines one at a time, and then appending the entire list every single time, which will result in the pattern 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, etc. Easiest way to resolve this would be to make sure you clear the text box before the for loop (i.e. - Move to the playlistTextArea.setText(null) down).

Resources