有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中,如何在字符串数组中的单词/数字之间添加一行?

让人困惑的标题,但我想知道的是如何将一长串单词或数字分开

我正在草草记下用户键入的城镇/城市的邮政编码。一些城镇有很多邮政编码,输出相当长

我想每100个字符把这些行分开,这样更容易阅读

I would like output to look like this: 

You asked me to search for place: Chicago, Il


Chicago, Il has zip codes: [60601, 60602, 60603, 60604, 60605, 60606, 
60607, 60608, 60609, 60610, 60611, 60612, 60613, 60614, 60615, 60616, 
60617, 60618, 60619, 60620, 60621, 60622, 60623, 60624, 60625, 60626, 
60628, 60629, 60630, 60631, 60632, 60633, 60634, 60636, 60637, 60638, 
60639, 60640, 60641, 60643, 60644, 60645, 60646, 60647, 60649, 60651, 
60652, 60653, 60654, 60655, 60656, 60657, 60659, 60660, 60661, 60663, 
60664, 60665, 60667, 60668, 60669, 60670, 60671, 60672, 60673, 60674, 
60675, 60677, 60678, 60679, 60680, 60681, 60683, 60684, 60685, 60687,  
60690, 60691, 60693, 60694, 60697, 60699, 60701]

^^^ My current output is that, but all in one line. ^^^

我想知道怎样才能把它修好。这是我目前的代码

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

/**
* In this class, I will obtain two private variables that are a type 
String and ArrayList.
 * The String will be the location that the user types in and the zip 
code will be the zip codes
 * that exist within that town/city.
 */
public class Place
{
 private ArrayList<String> zipCodes;
 private String location;

 /**
  * In this method, we find the file in which we will retrieve this 
  data. We put it in a Scanner and
  * put each line in an ArrayList that is ZipCodes.
  * @throws FileNotFoundException if the file doesn't exist.
  */
 public Place() throws FileNotFoundException
 {

    File zipsFile = new File("/Users/adanvivero/IdeaProjects/assignment 
 6/zips.txt");
    zipCodes = new ArrayList<String>();

    Scanner coordinates = new Scanner(zipsFile);

    while(coordinates.hasNextLine())
    {
        String lineScan = coordinates.nextLine();
            zipCodes.add(lineScan);
    }
 }

/**
 * In this method, we print out the zip code of the town/city in which 
the user typed in.
 * @throws FileNotFoundException We use this since we used a file in 
the String method, setZipCode
  * down below.
  */
 public void addPlace() throws FileNotFoundException
 {
    String theSummary = location + " has zip codes: " + setZipCodes();
    if(theSummary.length() > 100)
    {
        System.out.println();
        System.out.print(theSummary);
    }

 }

 /**
 * In this method, we retrieve the zip code of the city/town. I have 
two ArrayList since I don't need
 * to get the coordinates of the file, but rather only the name of the 
town and the zip code of it. Therefore,
 * I add the zip codes into one of the ArrayList, which in this 
instance happen to be our private one, and
 * the name of the location in another Arraylist.
 * @return We return a String that will be the zipCodes which is in an 
Array, but converted as a String.
 * @throws FileNotFoundException We retrieve the file in which these 
will come out in. If the file doesn't exist,
 * we throw a FileNotFoundException.
 */
public String setZipCodes() throws FileNotFoundException
{
    File zipsFile = new File("/Users/adanvivero/IdeaProjects/assignment 
6/zips.txt");
    //ArrayList<String> zips = new ArrayList<String>();
    zipCodes = new ArrayList<String>();
    ArrayList<String> codes = new ArrayList<String>();

    Scanner console = new Scanner(zipsFile);

    while(console.hasNextLine())
    {
        String z = console.nextLine();
        String [] zip = z.split("\t");
        String [] code = z.split("\t");
        if(location.equalsIgnoreCase(code[3]))
        {
            zipCodes.add(zip[0]);
            codes.add(code[3]);
        }
    }
    String theSummary = zipCodes.toString();
    for(int i = 0; i <= theSummary.length()-1; i++)
    {
        while(theSummary.charAt(i) == 100)
        {
            System.out.println();
        }
    }
        return zipCodes.toString();
 }

/**
 * In this String method, we as the user to type in a place and we 
return the place the user typed in so other
 * methods can use it.
 * @return it returns the String of the location the user types in.
 */
public String getLocation()
{
    Scanner wuddup = new Scanner(System.in);
    System.out.print("You asked me to search for place: ");
    location = wuddup.nextLine();
    return location;
}
}

所以我相信解决我的问题的方法是setZipCode()方法或addPlace()方法


共 (2) 个答案

  1. # 1 楼答案

    从addPlace()可以调用此方法来格式化输出

    这种方法的优点是可以:

    1. 将字符串拆分为任意长度
    2. 不会在邮政编码中间断线。<李>

    工作守则:-

    /**
     * Format a String to specific line length.
     * @param summary : Input string
     * @param maxLineLength Max line length.
     * @param delim String delimeter to be used for breaking the string like space or comma
     * @return the formated sting
     */
    public static String formatSummary(String summary, int maxLineLength, String delim) {
        //convert long string to array of word by delim and discard empty string.
        List<String> summarySplitByDelim = Arrays.stream(summary.split(delim)).filter(a->a.length() > 0)
                .collect(Collectors.toList());
        String newLine = System.getProperty("line.separator");
        StringBuilder formattedSummary = new StringBuilder();
        StringBuilder currentLine = new StringBuilder();
        for (String currentWord : summarySplitByDelim) {
            // Keep on adding word by word to currentline
            currentLine.append(currentWord.trim()).append(delim);
            //if current line execeed our line length, dump everything to formatedSummary and reset currentline
            if(currentLine.length() > maxLineLength){
                formattedSummary.append(currentLine).append(newLine);
                currentLine = new StringBuilder();
            }
        }
        //Add the last line if not added because the loop exited.
        if(currentLine.length() > 0){
            formattedSummary.append(currentLine).append(newLine);
        }
        return formattedSummary.toString();
    }
    

    调用类似formatSummary(data, 80, " ");的方法将产生输出

    Chicago, Il has zip codes: [60601, 60602, 60603, 60604, 60605, 60606, 60607, 60608, 60609, 60610, 60611, 60612, 60613, 60614, 60615, 60616, 60617, 60618, 60619, 60620, 60621, 60622, 60623, 60624, 60625, 60626, 60628, 60629, 60630, 60631, 60632, 60633, 60634, 60636, 60637, 60638, 60639, 60640, 60641, 60643, 60644, 60645, 60646, 60647, 60649, 60651, 60652, 60653, 60654, 60655, 60656, 60657, 60659, 60660, 60661, 60663, 60664, 60665, 60667, 60668, 60669, 60670, 60671, 60672, 60673, 60674, 60675, 60677, 60678, 60679, 60680, 60681, 60683, 60684, 60685, 60687, 60690, 60691, 60693, 60694, 60697, 60699, 60701]

  2. # 2 楼答案

    In addPlace()执行以下操作:

     String theSummary = location + " has zip codes: " + setZipCodes();
     String theNewSummary = "";
     for(int i = 0; i < theSummary.length()-1; i = i+100){
              if(i+99 < theSummary.length()-1)
              theNewSummary += theSummary.substring(i, i+99)+"\r\n";
              else
               theNewSummary += theSummary.substring(i, theSummary.length()-1);
    
     }
     System.out.print(theNewSummary );
    

    为了每行显示10个Zipcode:

      String theSummary = location + " has zip codes: \r\n";
      String[] zipCodes = setZipCodes().split(" ");
      for(int i = 0; i < zipCodes.length; i++){
           theSummary += " "+zipCodes[i];
           if(i%10 == 0 && i !=0)
               theSummary +="\r\n"
      }
      System.out.print(theSummary );