characters display of a text file in java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a text file which contains a line as a,b,a,b,a,b and I want to display the line as b,b,b,a,a,a
any assistance would be appreciated

Use BufferedReader's readLine() method to read a line from the file.
Use String's split() to split the line into tokens (characters in this case).
Sort the array returned from String.split() using Arrays.sort() (note that the order will be the opposite to that required so you should reverse through the array when printing), or store the array into an ArrayList and use Collections.sort() and specify your own Comparator.

public static void main( String[] args) {
String line="a,b,a,b,a,b";
String[] split = line.split( "," );
Arrays.sort( split );
for ( int i = split.length -1; i > 0 ; i--) {
System.out.print( split[i] );
System.out.print( "," );
}
System.out.print( split[0] );
}

Split the text based on ','
Just create an array and keep storing elements on that array , sort this array whatever way you want to , and the print the output

Let's break it into steps:
Open the file
Read the line from the file
Parse the line into individual elements
Add the elements to a data structure
Sort the data structure
Reverse the order
Display the data structure, either by rendering the contents or creating a String
Which part are you having trouble with?

Related

Use of java.txt files, polymorphism and delimiters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I need to read from a text file in java and pass that information through a polymorphic method. My idea is a CryptoWallet in a .txt file reading as coin, amount and value, where in the text file its represented as Bitcoin 100 1.25.
Ive got the code reading from the file and printing it, as below.
public class CryptoCurrencies
public static void main (String[] args) throws IOException
{
System.out.println("Welcome to your Crypto Wallet"
+ "\nCurrently, you only own one coin.");
File CryptoWallet = new File("/Users/curti/OneDrive/Desktop/crypto.txt");
Scanner scan = new Scanner(CryptoWallet);
String fileContent = " ";
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
continue;
}
My main issue is actually getting the text file too recognise the numbers as doubles and variables, and assigning them to run through a polymorphic method. I understand the polymorphism side, but if anyone has any ideas for a possible polymorphic method id really appreciate it, having trouble thinking at the moment!
Thanks everyone.
It is unclear what role polymorphism is supposed to have here.
Assuming that each row represents a record and each record has the same form then we can parse each row in an identical fashion. That allows you to extract the numeric values using the parse methods in the appropriate Number classes.
For instance...
while(scan.hasNextLine()) {
String line = scan.nextLine());
String[] tokens = line.split(" ");
String name = tokens[0];
int amount = Integer.parse(tokens[1]);
double value = Double.parse(tokens[2]);
}
p.s. obligatory comment that you shouldn't represent money in floating point variables.
Split the current line by space or "\s+" regex, check if the length is 3, then use the double.parse function from the double object on the 2nd and 3rd element in the array.

How to create an array of array list? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Hello I just had a question about a sorting problem I’m working through. I need to take a list a words and sort them by the first character. So basically I’m creating an array of each letter with a list inside the list. For example at position 0 of the array I could have a list of words that start with A. For position 1 it would be words that start with b. I figured out how to do this by hardcover a bunch of if statements for each letter. I guess my question is, is there a simpler way of achieving this without having to hardcode 27 if statements for each letter?
This is nicely done with the Java Streams API. The operation you ask for is called grouping (by).
The code below will stream over all elements of the array created by split, putting the elements in groups defined by a given function. The code below uses str -> str.charAt(0) as function, which basically says "from element str, get the first character, and this identifies the group", that is, the key.
Map<Character, List<String>> map = Arrays.stream(line.split(" "))
.groupingBy(str -> str.charAt(0));
The abovementioned code uses the functional programming style. Not everyone is familiar with this style, so below you'll find a solution using traditional style.
Map<Character, List<String>> map = new HashMap<>();
String[] words = line.split(" ");
for (String word : words) {
char first = word.charAt(0);
if (!map.containsKey(first)) {
map.put(first, new ArrayList<>());
}
map.get(first).add(word);
}
Why a map? Why not just an ArrayList?
A map has better lookup performance (time complexity of O(1)), while using a List requires you to traverse the list (time complexity O(n)).
Using charAt(0) I assume that none of the words is empty, i.e. has a length of 0.

best / better way to read / write arrays to firebase [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I was trying to find how to write/read arrays from my Firebase and I ended up with this. When I write I do:
String RestaurantIDs = "";
for(String RestaurantID : category.getRestaurantIDs()) { RestaurantIDs += RestaurantID + ","; }
DataToSave.put(CategoryFireBase.RestaurantIDs, "[" + RestaurantIDs + "]");
And when I read I do:
ArrayList<String> restaurantIDs = new ArrayList<>();
String[] Temp_restaurantIDs = document.get(CategoryFireBase.RestaurantIDs).toString().replace("[","").replace("]","").split(",");
for (String value : Temp_restaurantIDs){restaurantIDs.add(value);}
And I have 2 questions about it.
Is it ok that I'm saving it as long string instead of arrays?
If there is a way to read and write the array as an actual array, is it better then this?
Is it ok that I'm saving it as long string instead of arrays?
There is nothing wrong with that but it's more convenient to use arrays. For example, if you have in the database an array of restaurant ids, when you make a get() call, you can get that arrays directly as a list, without the need to split that long String.
If there is a way to read and write the array as an actual array, is it better then this?
Is it better because you can use specialized methods to update or remove elements within an array, as explained in the official documentation:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

Swap two columns of a file in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I am trying to write a method for swapping columns of a text file using java.
can someone show or tell me how to write a method to swap two columns of a file in java ? both columns are seperated by a space
One possible method:
Read in file and split data (see here reading tab delimited textfile java)
Overwrite file with same data read in, but column order switched.
Read every line of the file
ArrayList<String[]> aryL = new ArrayList<String[]>();
for each line of file
aryl.add(eachline.split(","));
for(String[] sArr: arrL)
//Swap the elements and print or write to file
you could read each line of a file and try
String buffer = "";
//for each line of input
String[] columns = line.split(" ");
buffer+= columns[1] + " " + columns[0] + "\n";
//end for
then overwrite the file with your buffer String

In Java, what's the best way to get numbers from a one-line String? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
For example:
input:
14 5 1
What's the best way to get these three values into three int variables?
Also, does it make any difference if we were dealing with double values?
Using Java 8 you can get the whole string into a stream of numbers like so:
IntStream intStream = Arrays.stream(input.split(" ")).mapToInt(Integer::parseInt);
From there, you can convert the Stream to an array:
intStream.toArray();
You can act on it directly:
intStream.forEach(n -> {
// do something here with n
});
...and much more: http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
Edit: As Chris pointed out, IntStream has a few more utilities tailored specifically to Integers: http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
Have fun!
Use the Scanner class.
Scanner scan = new Scanner("14 5 1");
System.out.println(scan.nextInt());
System.out.println(scan.nextInt());
System.out.println(scan.nextInt());
This snippet would output
14
5
1
You can use nextDouble() instead of nextInt() when working with doubles
If you don't know how many numbers you are going to have you can use a while loop to keep reading numbers. You could rewrite the above as
Scanner scan = new Scanner("14 5 1");
while(scan.hasNextInt())
System.out.println(scan.nextInt());
The output should remain the same. Use it if it's any simpler for your program.
you can get those numbers in one line, assume you already did it and stored on a String s;
you can split them into a String Array by doing String [] k = String s.split(" "); , this will split the String s onto 3 different Strings in one String array separated by space, after you do that, convert them to use wherever you want like these,
int a = Integer.parseInt(k[0]);
double b = Integer.parseDouble(k[1]);
double c = Integer.parseDouble(k[2]);

Categories