![](/img/trans.png)
[英]Changing input so in can take any length of string, problems with output
[英]How to take input as String given the String Length
給定字符串長度,如何從用戶輸入作為字符串
問題鏈接:
http://www.practice.geeksforgeeks.org/problem-page.php?pid=295
我的方法:
我使用Scanner完成任務以獲取測試用例的數量,然后將String長度作為輸入:
但是我很困惑如何采用指定長度的字符串。我的搜索發現沒有方法或構造函數可以采用指定長度的字符串。
有人可以指導嗎?
下面是我的代碼:
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int Strlength=sc.nextInt();
String strnew=sc.next(); //How to take Stringofspecified character
..........
.........
}
您無法做到這一點,如果String的長度與給定的輸入不匹配,您可以簡單地迫使用戶重新插入String。
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
int Strlength=sc.nextInt();
String strnew = null;
while (strnew == null || strnew.size() != Strlength) {
strnew = sc.next();
}
..........
.........
}
一種方法是插入某種測試,例如:
String strnew;
do{
strnew=sc.next(); //How to take Stringofspecified character
}
while(strnew.length() != Strlength);
我想出了一種方法。
Scanner sc = new Scanner(System.in);
int strLength = sc.nextInt();
sc.nextLine();
String strInput = sc.nextLine();
if(strInput.length()>strLength)
{
str = str.substring(0, strlength);
}
// Now str length is equal to the desired string length
String S = "";
Scanner sc = new Scanner(System.in);
int D = sc.nextInt();
for(int i=0;i<D;i++) {
S = S + sc.next();
}
System.out.println(S);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.