I am trying to find a way to bubble sort a text file that looks like this:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
Essentially I want them to be in the order of release date for example a game released on 01/25/16 would come before a game released in 06/26/16 and it would create a new file like this:
04/26/16 Sega 3D Classics Collection
06/24/16 Tokyo Mirage Sessions #FE
07/14/16 Batman: Arkham Underworld
I am certain that there will be a for loop involved as each line will be an element of an array with swapping methods and a temporary value for comparison sake to swap the order of the but I cannot think of a way to write the new order into a new file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws IOException{
File file = new File("releasedates.txt");
String[]arr;
arr = input(file);
output(file,arr);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(File file, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByMonth(String[]info){
String temp;
for (int j = 0; j < info.length; j++) {
for (int i = j + 1; i < info.length; i++) {
if (info[i].compareTo(info[j]) < 0) {
temp = info[j];
info[j] = info[i];
info[i] = temp;
}
}
}
}
}
Just invoke the sortByMonth inside your output method:
Also, there is no need to pass the File object to output as it is not used.
public static void output(String[] info) throws IOException{
sortByMonth(info);
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
Related
So I am trying write some code to find a way to bubble sort an existing text file that I have collected the information in a form of an array and it looks like this:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
Essentially I want them to be in alphabetical order and it should make a brand new file that looks like this:
Batman: Arkham Underworld
Sega 3D Classics Collection
Tokyo Mirage Sessions #FE
The problem is I do not know how to remove the date of the string that it is originally part of. I think there should be some kind of function like indexOf() like in javascript. I would assume that after the extraction of the names. Then the sorting would be the same as the one I have done for the sorting of dates.
This is the code I have done:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws IOException{
File file = new File("C:/Users/cyrus/Downloads/Lab 11/releasedates.txt");
String []arr = input(file);
output(file,arr);
outputSort1(file, arr);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(File file, String[] info) throws IOException{
FileWriter writer = new FileWriter("C:/Users/cyrus/Downloads/Lab 11/fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByMonth(String[]info){
String temp;
for (int j = 0; j < info.length; j++) {
for (int i = j + 1; i < info.length; i++) {
if (info[i].compareTo(info[j]) < 0) {
temp = info[j];
info[j] = info[i];
info[i] = temp;
}
}
}
}
public static void outputSort1(File file,String[] info) throws IOException{
sortByMonth(info);
FileWriter writer = new FileWriter("C:/Users/cyrus/Downloads/Lab 11/fileNameSorted1.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByName(String[]info){
//this isn't really finished, I am unsure on how to extract JUST the name of the games
}
}
There are several ways to sort the lines. suppose you put all the lines in a list and sort that list, before the sort, you also remove the date.
Using Java Stream 8
List<String> lines = Arrays.asList("04/26/16 Sega 3D Classics Collection",
"07/14/16 Batman: Arkham Underworld",
"06/24/16 Tokyo Mirage Sessions #FE");
List<String> newLines = lines.parallelStream()
.map(line-> line.substring(line.indexOf(" ")))
.sorted((line1, line2)->line1.compareTo(line2))
.collect(Collectors.toList());
newLines.forEach(System.out::println);
i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();
I am trying to reorder an ArrayList alphabetically for an assignment. I am not allowed to use any methods for automatically sorting, it has to be done manually. This is the code I tried, but it does not even run. I appreciate any input on this.
import java.util.ArrayList;
public class SortArrayList {
public static void main(String[] args) {
ArrayList<String> values = new ArrayList<String>();
public static void main(String[] args) {
ArrayList<String> values = new ArrayList<String>();
values.add("car");
values.add("bear");
values.add("apple");
values.add("xray");
sort(values);
for (int i = 0; i < values.size(); i++)
System.out.println(values.get(i));
}
public static void sort(ArrayList<String> x) {
String temp;
for (int i = 0; i < x.size() - 1; i++) {
for (int j = i + 1; j < x.size(); j++) {
if (x.get(i).compareToIgnoreCase(x.get(j)) > 0) {
temp = x.get(i);
x.add(i,x.get(j));
x.add(j,temp);
}
}
}
}
}
The lines
x.add(i,x.get(j));
x.add(j,temp);
are adding more elements to the ArrayList. You should change them to
x.set(i, x.get(j));
x.set(j, temp);
so that it replaces the elements at those positions.
Unless the multiple calls to public static void main(String[] args) was a typo when you copied it across for your question this would cause issues when running the program as it won't know where to start
I'm programming in Java. I'm not good at programming, but I'm trying.
I managed to create a file that generates an array of 10k random (in range 1 through 1 million) numbers into a text file. This class is called 'CreateDataFile'
What I'm trying to do now is read the array from the text file created in 'CreateDataFile' from a completely different class. This new class is called 'ProcessDataFile'
The first thing I thought about doing is 'extends' the class. So both classes communicate.
The thing is, I know how to create a for loop in a program and then find the largest number. I just don't understand how to read this text file, and create a for loop that processes from the text file and finds the max value.
Here's my CreateDataFile class
import java.io.*;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int [] integers = new int[10000];
Random r = new Random();
try{
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i <integers.length; i++) {
int number = r.nextInt(1000000)+1;
p.print(" " + number);
}
p.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Now this generates the numbers I need into a text file called dataset529.
If everything was in one class, I'd just create a for loop.. something like
int max = integers[0];
for(int i = 0; i<integers.length; i++){
if (integers[i] > max)
System.out.println(integers[i]);
}
But as I'm creating my ProcessDataFile class, I'm having a hard time reading the text file created from the CreateDataFile class.
Any ideas on how I can read this text file and run a for loop over it to find the max number like I used above?
Thanks, any help would be appreciated.
First of all, you should write in the file each number on one line so that it's easier when you read the numbers from the file. This can be done just by doing:
p.print(number + "\n");
After that, you can use this code to get the max of all the numbers:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "dataset529.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[10000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while((temp = br.readLine()) != null) {
if(temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
for(i = 0; i < numbers.length; i++)
if(max < numbers[i])
max = numbers[i];
System.out.println(max);
}
Write the content of each number on new line. While reading the file, maintain a max element.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int[] integers = new int[10000];
Random r = new Random();
try {
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i < integers.length; i++) {
int number = r.nextInt(1000000) + 1;
p.print(number + "\n");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now read the file line by line.
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
int max = Integer.MIN_VALUE;
String line = null;
BufferedReader br = new BufferedReader(new FileReader("dataset529.txt"));
while ((line = br.readLine()) != null) {
int num = Integer.parseInt(line);
if (max < num) {
max = num;
}
}
}
System.out.println(max);
}
Got an Error with NullPointerException . (cs106A handout 6 - Name Count using hash map)
Debugger told me the problem located # String input variable. I got no idea how to solve it.
thanks for reading.
import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader.*;
import java.lang.*;
public class NameCounts extends ConsoleProgram{
// hashmap
static HashMap<String,Integer> myUniq = new HashMap<String,Integer>();
static String input ;
static public void insertName(){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:");
// if keyboard input contain new unique name ,
// store it in the hashmap and count the value +1
input = br.readLine();
if(input.equals("")) break;
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
}
}
catch (IOException e){ };
}
// print and show every single hash map and count value
static public void releaseUnique(){
for(int i= 1 ; i < myUniq.size() ; i++){
System.out.println("Entry"+"[" + input + "]"+"has count"+myUniq.get(input));
}
}
public static void main (String[] args){
insertName();
releaseUnique();
}
}
I think you should change
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
to
if(myUniq.containsKey(input)) {
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input, temp);
} else {
myUniq.put(input, 1);
}