Use of java.txt files, polymorphism and delimiters [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 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.

Related

I have a string with a number and a letter, is there a way to move the integer into a separate int variable? [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 3 years ago.
Improve this question
So I'm working on a school project and it includes a Combined Gas Law calculator where the user may input the temperature in °celsius (e.g. 1°C) and the code converts it to kelvin; if the user's input is in kelvin already, it does not do that and continues with the equation. So does anyone know how I can separate the two data types into two different variables in Java?
You could split over a specific string (degree character for example), store in a String array and parse the first element. Something like this:
String str = "47°C"
String[] strArray = str.split("°");
int number = Integer.parseInt(strArray[0]);
Congratulations, you are working on something but not writing it's code. I can tell you a few tips about how to implement it's code.
You have a string that has some numbers in it, and also has unit. Try searching 'How to extract numbers from a string'. Now you have a number.
Find the unit in the string by looking the last character in the string.
If the condition is ok for your homework, calculate the new value.
Print the result.

Is it possible to find a word in a txt file and print the line as a 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 3 years ago.
Improve this question
I am stuck on some homework as i am new to java and still learning. I am wondering if it is possible to find a word in a .txt file and output the line that the word is on. I also need to allow a user to make a choice based on what is displayed back.
Example :
Word is Details
Txt file contains
Details on lion
Details on tiger
Output : "Details on tiger"
Thank in advanced for any help
This question has been answered before, but anyway You can go with this apporach.
Simply put:
Create a Scanner object and pass the required file into the
constructor as a new file object.
Iterate over the file with a
while loop until you find the specified string.
In order to store the lines that contains the desired word,we decalre a new string variable
Here's the code snippet:
Scanner scanner= new Scanner(new File("filename.txt"));
String lines = "";
while(scanner.hasNextLine()){
String stringLine = scanner.nextLine();
if(stringLine.indexOf("YOUR_WORD") != -1){
//print whatever you want here
System.out.println(stringLine);
//add every line that contains stringLine into another string;
lines+=stringLine;
}
}

how to split a text file by line gaps in java [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 5 years ago.
Improve this question
I am reading a text file in Java that looks like this,
"
Q1. You are given a train data set having 1000 columns and 1 million rows. The data set is based on a classification problem. Your manager has asked you to reduce the dimension of this data so that model computation time can be reduced. Your machine has memory constraints. What would you do? (You are free to make practical assumptions.)
Q2. Is rotation necessary in PCA? If yes, Why? What will happen if you don’t rotate the components?
Q3. You are given a data set. The data set has missing values which spread along 1 standard deviation from the median. What percentage of data would remain unaffected? Why? "
Now, I want to read this file and then store each of these sentences(questions) in a string array. How can I do that in java?
I tried this,
String mlq = new String(Files.readAllBytes(Paths.get("MLques.txt")));
String[] mlq1=mlq.split("\n\n");
But this is not working.
Try this
String mlq = new String(Files.readAllBytes(Paths.get("MLQ.txt")));
String[] mlq1=mlq.split("\r\n\r\n");
System.out.println(mlq1.length);
System.out.println(Arrays.toString(mlq1));
This should do it by line gap of 2 lines.
File file = new File("C:\\MLques.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st + "\n");
}
I think it will work.
This is a piece of code from one of my project.
public static List<String> readStreamByLines(InputStream in) throws IOException {
return IOUtils.readLines(in, StandardCharsets.UTF_8).stream()
.map(String::trim)
.collect(Collectors.toList());
}
But!!! If you have really big file, then collecting all content into a List is not good. You have to read InputStream line by line and do all you need for every single row.

What is the easyest way to transform the In.ReadInts function from Java to C#? [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 7 years ago.
Improve this question
I have the following code:
public class Search
{
public static void main(String[] args)
{
int[] whiteList = In.readInts(args[0]);
while(!StdIn.Empty())
{
int key = StdIn.readIn();
...
}
}
%java Search largeW.txt < largeT.txt
How to transform it to C# ?
Here you are:
Console.WriteLine("Input your number: "); // input 4, press enter
var theVar = Convert.ToInt32(Console.ReadLine()); // theVar is 4
Hope this help.
Java and C# aren't too different. You just need to know how to read STDIN, right? For a console application, use Console.ReadLine() or one of the other methods provided by the Console class.
Also keep in mind when converting:
1. With method names, you capitalize the first letter of EVERY word, i.e. MyMethod(). (important because Main() needs to be capitalzed)
2. All classes are inside a namespace block.
3. All of your type conversion tools are under Convert
4. File is a static class. You don't create instances of it like in Java. I recommend looking at File.ReadAllLines(string name).
Other than that the syntax is very similar and it should be fairly easy to convert between the two languages.

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