1.11M Members

Break line after a condition met

 
0
 

Hi forum,
I've got a question for the pros. I am making a program that has map<String, String> map = new TreeMap<String, String>();
and a Scanner to read a file contains some data which is assigned to map.put(); method. The data is something like this:
UK USA Canada Australia etc. The country names are separated with a "tab". All the data is on one line of a text file. I just want that when I print the country names and when system prints the data up to 5 tabs it will start a new line and then print the other 5 tabs and then again a new line and so on. I hope that someone will help me out.

             import java.io.*;
             import java.util.*;

              public class Countries {

              public static void main (String [] args) {

               File file = new File("C:/Countries.txt");

            Scanner reader = new Scanner(file);
           Map<String, String> map = new TreeMap<String, String>();

            String data[];

           while(reader.hasNext()) {

           data = reader.nextLine();

           map.put(data[0], data[1]);

          System.out.println(data);// printing data up to 4/5 tabs then break the line 
            System.out.println(data);// printing next 5 tabs and break the line and so on.
         }
           }
              }
 
2
 

Your requirement is so simple, but why your implementation is so complicated? Or maybe I am missing something in your requirement. Let me rewrite your requirement and see if it is the same.

1.Read data in from a file
2.The data consists of different country names with a tab character in between
3.Print out the country name, 5 names for each line

Now, my question would be that do you need to save the data that you read in from the file? If so, do you need to do a search in the data later on? Can your read-in data be duplicated? If it can, do you have to keep only unique data?

These questions would help others (including myself) to understand your requirement better. For now, I am making assumptions from your requirements.

Anyway TreeMap is not suitable to your requirement. You need to understand what TreeMap is used for (map a value pair of a key & value given all keys are unique).

Speaking of your print out, you need an integer as a counter. Don't forget to start from 0. The way to print out depends on whether or not you need to store your data after read-in.

If you do not need to store your data, it is very simple. You read in each line of the file content, then split the line string using split(DELIMITER) method of String. The DELIMITER is a regular expression string, and in your case it could be "\\s+" which means at least one white space characters (space, tab, or newline character). Once you split your line data, print out each element of the split data and don't forget to keep counting with your counter variable. Once the counter value hits whatever number you want to print out in a line, reset the counter and print out a new line (using System.out.println()).

 
0
 

your 1st mistake is at line 17.
you can't store string value to String array witout specifying location.You haven't specify location at which place you want to store your 1st country name.

Also you haven't take delimiter, upto which you want to read the file content.
delimiter may be comma, space, tab, new line.

So provide delimiter split your 1st line into no. of chunks(part) with specified delimiter and then store each value to different location of String array.

you can do this thing by using BufferedReader class and split method of String class.
then at last when you print your data print upto 5 tab only(or in string array upto first 4/5 location then remaining and so on....).

 
0
 

Hi everybody, Thanks all of you for the replies you made regarding my question. Taywin you asked some questions about my program that now I realized I should've explained earlier. But I abridged the whole story to make it shorter for the forum readers. Ok, so the basic idea of my program is that there is text file named "Countries.txt" with countries and corresponding city names stored in it. Something like this:
USA:Chicago(tab)Boston(tab)New York(tab)California(tab)Washington ..
UK:London(tab)Birmingham(tab)Manchester(tab)Bradford(tab)Buckingam ......
(tab) is \t delimeter to separate city names
There can be 50 city names for each country. Now what I want is to read this file and store the data so I can make queries like this:
If user type UK the program should display the first 5 city names on first line of output then next 5 on the next line and so on. And if user type exit the program will exit.

Hope it will now be clear for you and you will next post would be a great help.

Thanks for all of you.

Peace

 
0
 

Thanks for clarification. Now, I understand why you want to use TreeMap. Yes, you could use TreeMap; however, you need an array or some sort of collection type object to hold all of your city data. You could use the country as key, and the array/collection type object as value. The array/collection type can also be your own customized class.

// Your customized object may be as follows...
import java.util.ArrayList;
class CityCollection {
  private ArrayList<String> cityName = new ArrayList<String>();
  public CityCollection() { }  // optional if you want to add anything else

  // other implementation, such as addCity(), addCities(),
  // getCities(), toArray(), etc...
  ...
  ...
}

// Then in your main program
Map<String, CityCollection> map = new TreeMap<String, CityCollection>();
...
...
// When you split each line, you have to extract the country name out for your
// TreeMap key. You could use indexOf(':') to find the substring you want, or
// split(":") and use the first element from the split value as the country.
// Whatever works for you.
...
// After you extract the key out from the line string, split it using regex
// I mentioned in my previous post. That should give you all the cities in
// a String array. Iterate through each of that and add to your key.
// One thing you need to keep checking is that if you cannot obtain the value
// of the collection (using get()) from the hash, you need to create one first.

// Create new collection before move on
if (map.get(key)==null) { map.put(key, new CityCollection()); }

// At this point, the tree at key will have CityCollection object for you.
map.get(key).addCities(THE_STRING_ARRAY_FROM_SPLIT);

Hope this would give you an idea of how to go forward.

PS: You may need to either upcase/downcase the key value if you want case-insensitive checking with user input later on. For example, your file contains USA as country name but a user enters usa in the search, do you allow that to happen so that it can still be found?

 
0
 

This is my code but I'm still getting my output on a single line. Please help

package countries;

import java.io.File;

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;


public class Airports {



    public static void main(String[] args) throws Exception{

       File file = new File("C:/Countries.txt");
       Scanner reader = new Scanner(file);
       Scanner input = new Scanner(System.in);
       String data[] = null;
       String search;
       int counter = 0;
      Map<String, String> codes = new TreeMap<String, String>();

      while (reader.hasNext()){
      data = reader.nextLine().split(":");
      String key = data[0];
      String value = data[1];
      codes.put(key, value);


      search = input.next();
      if(codes.containsKey(search)){

        String cities = codes.get(search);  
      System.out.print(cities + " ");
      counter ++;
      if( value.length()>3){
      System.out.print('\n');
      counter = 0;
      }
      }
      }//while
       }
       }

The out put of this program is something like this
eng
London Birmingham Manchester liverpool Bradford New Castle Edinburgh

But I want to have the only five cities name on each line.
Please help.

Thanks

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: