【问题标题】:How to take a string with some specific length in java [duplicate]如何在java中获取具有特定长度的字符串[重复]
【发布时间】:2017-05-23 15:45:05
【问题描述】:

我是 Java 新手,正在研究一些字符串示例。我正在获取一些我需要的字符串,然后为每个字符串指定一些长度,这也是用户的输入。一旦我得到长度整数,我就试图获得相同长度的字符串。如果超过或小于,那么我会抛出错误。但我坚持如何得到这个。

在几个地方我得到 java.util.InputMismatchException 我的代码:

package Test;
import java.util.Scanner;

public class TestInputString {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
         int Num = sc.nextInt();
         for(int i=0; i<Num; i++){
             int length = sc.nextInt();
             String str1 = sc.next();

         }
    }

}

我的输出应该是这样的。 输出:

No. of String - 3

Length : 4
String : ABCD

Length : 5
String : ABCDE

Length : 6
String : ABCDF 

【问题讨论】:

    标签: java string io


    【解决方案1】:

    而不是:String str = sc.nextLine();

    使用这个:String str = sc.next();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 2010-09-15
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      相关资源
      最近更新 更多