best solution for java txt project [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Like topic says I'm looking for the best way to:
I got .txt file. In this file there are for example:
Matthew Sawicki 25\n
Wladimir Putingo 28\n
Barracko Obamaso 27
Whats the best way to write a program that opens this file, checks out the biggest number and then prints out that?
I was thinking about: open file -> check each line with hasNextLine method saving the biggest number (addin i for measuring the lines - 1, 2, 3) and then close file and open again and then somehow prints out that line
Ok there goes edit then.
By the way I have to write name of file in console to open it. And I have to use Scanner.
My code:
Scanner scanner= new Scanner (System.in);
File file = new File (scanner.nextLine);
scanner = new Scanner (file);
int temp=O;
int i=0;
while (scanner.hasNextLine) {
String word1=scanner.next;
String word2=scanner.next;
String word3=scanner.next;
If(word3>temp)
temp3=word;
i++; // now i get the i id of the line with the biggest number
And now I'm thinking bout reopen file and loop again to print out that line with the biggest number(By for instance if(newWord3==temp))
is it a good idea? And how to reopen the file? can anyone continue the code?

Assuming that this file will always be in the same format here's a snippet that does what you want with no checking to make sure that anything is in the wrong place/format.
//Create a new scanner pointed at the file in question
Scanner scanner= new Scanner(new File ("C:\\Path\\To\\something.txt"));
//Create a placeholder for the currently known biggest integer
int biggest = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
//This line assumes that the third word separated by spaces is an
// integer and copies it to the `cndt` variable
int cndt = Integer.parseInt(s.split(" ")[2]);
//If cndt is bigger than the biggest recorded integer so far then
// copy that as the new biggest integer
biggest = cndt > biggest ? cndt : biggest;
}
//Voila
System.out.println("Biggest: " + biggest);
You'll want to verify that the number in question is there, and that you can handle the case that a line in your text file is malformed

There are several ways to do what you want. The way you described can work, but as you noted it requires to scan the file twice (in the worst case, which is when the row you have to print is the last one).
A better way which avoid to reopen the file again is to modify your algorithm to save not only the biggest number and the corresponding row number, but saving the whole line if the number is bigger than the one previously saved. Then, when you're done scanning the file you can just print the string you saved, which is the one containing the biggest number.
Note that your code will not work: the if is comparing a String with an int, and also there's no temp3 variable (that's probably just a typo).
To follow my suggestion you should have something like this:
int rowNumber = Integer.parseInt(word3);
if(rowNumber > temp) {
temp = rowNumber;
tempRow = word1 + " " + word2 + " " + word3;
}
then you can just print out tempRow (which you should define outside the while loop).

It's all fine now. I've made a simple mistake in my file (an empty enter at the end) so i coudnt figure out how to do it.
Thanks for ur effort and gl!.

Related

While Loop with Scanner.hasNextInt() skips last item

I was practicing using Scanner and I've encountered an strange occurance and i would like some help from the community to understand this.
I've a text file with the following numbers
1,2,3,9
5,9
3
reading the text file with the following java code
fsc = new Scanner(new File(fileName));
fsc.useDelimiter(",");
while (fsc.hasNextLine()) {
while (fsc.hasNextInt()){
System.out.print(fsc.nextInt() + ",");
}
System.out.println();
fsc.nextLine();
}
and the results always skips the last number.
1,2,3,
5,
3,
How do i make it not ignore the last item?
Edit: Some solutions calls for splinting them to an array and converting the strings to integer however I would like to explore using Scanner.nextInt() instead
Edited 2: I'm so sorry seems many misunderstood the question. What i meant was missing is the last digit of each line is missing!
This is because you removed the standard delimiters, i.e. linefeeds. You need
fsc.useDelimiter("[ ,\r\n]");
So this becomes
fsc = new Scanner(new File(fileName));
fsc.useDelimiter("[ ,\r\n]");
while (fsc.hasNextLine()) {
while (fsc.hasNextInt()){
System.out.print(fsc.nextInt() + ",");
}
System.out.println();
if (fsc.hasNextLine())
fsc.nextLine();
}
Just add one condition to check new line,

Why can't I read indefinately doubles using this loop? [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 6 years ago.
Improve this question
I'm trying to read some data from a user and do some very simple calculations with them, but for some reason I can't explain, the program stops after first 2-3 inputs (given they are doubles). Can someone explain this behaviour?
My code:
Scanner in = new Scanner(System.in);
System.out.println("Enter your values, 'q' to quit: ");
double average, input, smallest, largest, range;
average = smallest = largest = range = Double.parseDouble(in.nextLine());
int counter = 1;
while (in.hasNextDouble()) {
input = Double.parseDouble(in.nextLine());
smallest = input < smallest ? input: 0;
largest = input > largest ? input: 0;
average += input;
counter++;
}
Consider this input:
1.23
4.56 7.89
To Scanner this looks like a valid sequence of three doubles on two separate lines. When you call nextLine to obtain the first double, it works fine, because the number occupies the entire string.
When you do the same for the next double, the string that you try to parse looks like this:
"4.56 7.89"
This string is not a valid double, so you cannot parse it.
One approach to deal with this problem is to call nextDouble, and avoid parsing altogether. Pairing up hasNextDouble() with nextDouble() has an advantage of not requiring users to put their data on different lines.
Note: The first call to Double.parseDouble(in.nextLine()) happens without checking that Scanner has next double, so your program could crash on initial bad input.

How to read a text file by skipping first and last line in a file [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 wanted to read a file line by line and store it to a variable. But, I want to skip the first and last line and store it to variable. How to do that?
Kindly help with a Java code to achieve this.
In Java 7 or Java 8 :
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
if(!lines.isEmpty()) {
lines.remove(0);
}
if(!lines.isEmpty()) {
lines.remove(lines.size() - 1);
}
Remove the if conditions if you are certain the files contain at least 2 lines.
I recommend you to use an ArrayList to read the full file:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now that you have stored all the lines of your file (as an ArrayList of String) you can operate with the data.
To operate with the data you just have to iterate through them by a loop:
for(int i = 1; i < list.size() - 1; i++)
{
String line = list.get(i);
System.out.println(line);
}
Look that I start on the position 1 and ends on the position list.size() - 1 to avoid the first and the last line of the file.
If you want to store your first line and your last line you can do:
String firstLine, lastLine;
firstLine = list.get(0);
lastLine = list.get(list.size());
I expect it will be helpful for you!

Open a text file and find a word and point to that word

I need to open a log file (.txt) and to go to that specific word.
Ex:- If im searching "MyTextWord" in the text file, it should open the default editor and go to the word "MyTextWord".
If it's in the 100th line it should go there, so that it shows 100th line and onwards.
Can it be done for linux and windows?
Depending on which editor is the default, yes it is doable. For example if you use Sublime Text you can open files with sublime somefile.txt:X:Y where X is the line number and Y is the column or character position. I'm sure most decent editors have similar capabilities, I'm not sure if there is any standards for this though.
So basically you would have to pre-process the log in question to find the line number and character position, start the editor with some additional parameters. As far as default editor goes, that would be more difficult since they probably don't share the same parameters for specifying line/column. And some, such as windows notepad probably don't support this kind of thing at all.
Here is a way to open NotePad for windows. I'm not sure if you are able to search and select text within the process itself...I'll check into that.
You can also check out the Desktop javadocs.
I think, past a few days I was developing a simple project which involved the same thing.
You can use Scanner to scan the file for the data. And then loop through it to get the data.
I would paste the code here and I would share the post link with you, so that if you need any further info, you can get it from there.
You can pass the string as the parameter to the method.
String character = sc.next(); // read character...
// Find the character
System.out.println("Searching now...");
getCharacterLocation(character); // here is the parameter as character
File reading function is below:
File file = new File("res/File.txt");
Scanner sc = new Scanner(file);
int lineNumber = 0;
int totalLines = 0;
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line...");
sc.close();
sc = new Scanner(file);
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
String characterInLine = sc.nextLine().toLowerCase();
if(characterInLine.indexOf(character.toLowerCase()) != -1) {
found = true;
}
lineNumber++;
if(sc.hasNextLine())
sc.nextLine();
}
System.out.println("Searching complete, showing results...");
// All done! Now post that.
if(found) {
// Something found! :D
System.out.print("'" + character + "' was found in the file!");
} else {
// Nope didn't found anything!
System.out.println("Sorry, '" +
character + "' didn't match any character in file .");
}
sc.close();
Yes, I know its a bit messed up code, because I like writing comments and I like to get information of what ever process is being executing and has done executing.
To get the whole code for this, go to the link below.
http://basicsofwebdevelopment.wordpress.com/2014/05/27/scanning-file-for-particular-string-or-character-searching/

Baby names not working [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 9 years ago.
Improve this question
Hi i have a program that doesnt seem to be registering. I am fairly new so I would appreciate any help and there might be stupid mistakes made :/
But the point of the program is the enter a name and then find the name in a file called names.txt and then show the popularity of the name throughout the century. I currently have a program that doesnt seem to be working. Help Please
import java.io.*;
import java.util.Scanner;
public class Babynames{
public static void main (String[] args)throws FileNotFoundException{
Scanner reader = new Scanner(new File("names.txt"));
Scanner input=new Scanner(System.in);
System.out.print("What name would you like to search up: ");
String name = input.nextLine();
Scanner lineScan = new Scanner(name);
String thisname = lineScan.next();
if (name.equals(name))
{
while (lineScan.hasNextInt())
{
int next = lineScan.nextInt();
for (int i = 1900; i <=2000; i+=10)
{
System.out.print(i + next);
}
}
}
else
{
System.out.println("File not found! Try again: ");
String filename = input.nextLine();
Scanner lineScan2 = new Scanner(name);
}
}
}
Edit
it just asks for the name and after that the program ends
Your assignment seems to be:
Accept a baby name as input
find that name in a file that includes some information about that name
output the result which includes the info about the name.
From your code, I'm making an educated guess that a line in your file looks like:
name value value value value value value value value value value value
Where the values represent the popularity of the name 1900 - 2000 by decade (11 values)
So, your program would need to:
Get the user input (name) from System.in using a Scanner .
Open the file
Loop, reading a line from the file
Split the line by space (" ") into a String[] array
Compare the first element (array[0]) to see if it's your name
if it is, go through the rest of the array and output the values

Categories