【问题标题】:Getting Weird Output on Java (New to Code)在 Java 上获得奇怪的输出(代码新手)
【发布时间】:2018-09-18 02:55:51
【问题描述】:

输入是 2013 年 4 月 3 日,输出应该是 2013 年 4 月 3 日,但是我一直得到 3, 2013-Apri-20 的输出

 import java.util.Scanner;
    public class DateConversion {
    public static void main( String [] args ) {


    Scanner sc = new Scanner ( System.in );


    System.out.println("Enter the date: ");
    String temp = sc.nextLine();

    String day =temp.substring(6);
    String month = temp.substring(0, 4);
    String year = temp.substring(9, 12);

    System.out.println(day + "-" + month + "-" + year);

    sc.close();


     }
   }

【问题讨论】:

标签: java output


【解决方案1】:

String 类 substring 方法将字符串从 startposition 拆分到 endposition-1 substring(start, end-1)

Scanner sc = new Scanner ( System.in );


    System.out.println("Enter the date: ");
    String temp = sc.nextLine();

    String day =temp.substring(6,7);
    String month = temp.substring(0, 5);
    String year = temp.substring(8, 12);

    System.out.println(day + "-" + month + "-" + year); //3-April-2013

    sc.close();

【讨论】:

    【解决方案2】:

    您的day 子字符串仅包含一个值(因此它从第六个字符开始到输入的结尾)。我会使用String.split 来获取令牌。喜欢,

    String temp = "April 3,2013";
    String[] tokens = temp.split("[\\s,]");
    System.out.printf("%s-%s-%s%n", tokens[1], tokens[0], tokens[2]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2014-12-03
      相关资源
      最近更新 更多