How to print only specific parts of a string in java?

不想你离开。 提交于 2019-12-24 17:23:54

问题


I am writing a program that writes a letter using specific parts of a string.

Here is what I have so far (I am only a beginner)

import java.util.Scanner;

public class AutoInsurance {

    public static void main (String[] args)
    {
        Scanner scan=new Scanner (System.in);
        System.out.print("Enter Name:");
        String Name;
        Name=scan.nextLine();
        System.out.print("Enter Street Address:");
        String Address;
        Address=scan.nextLine();
        System.out.print("Enter city, state, and zip code:");
        String Location;
        Location=scan.nextLine();
        System.out.println();
        System.out.println();
        System.out.println("Dear "+Name+",");
        System.out.println(" You have been selected to receive this offer of auto insurance from");
        System.out.println("Allspam Insurance Company! Drivers from "++" saved an average "); // I just want it to print the city here, between ++

        // I will finish coding once I figure this out, but I'm stumped
    }
}

回答1:


The best you can do here is to split your Adress string, by commas, and grab the first value from the resulting array.

Take a look at this question for more details on splitting a string in Java.

I suggest the following in your code:

String[] AddressParts = Address.split(",");
String City = AddressParts[0];
System.out.println("Allspam Insurance Company! Drivers from "+City+" saved an average ");

Cheers!




回答2:


To break a string apart use this method

    String s = "abcde";
    String p = s.substring(2, s.length);

From here, you can find out which parts of the string you want.




回答3:


It would be a better style to use different variables for each part (city, postal and zip code).

Otherwise you might

  • Change the order of the elements, take postal into the middle and than do String city = Location.split("[0-9]")[0];
  • Define a token that the users inputs to seperate the data (e.g. #) and than do String city = Location.split(#`)[0];


来源:https://stackoverflow.com/questions/23019070/how-to-print-only-specific-parts-of-a-string-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!