我希望能够使用StringBuilder强制输入10个字符。我知道可以将其设置为最大字符数限制,但我可以精确设置为10吗?

也许是这样的:

import java.util.Scanner;
public class Phonenumber
{
public static void main(String[] args)
{
  Scanner input = new Scanner(System.in);
  StringBuilder num = new StringBuilder(System.in);

  System.out.println("What is your 10 digit phone number?");
  num = input.nextStringBuilder();
  while(!(num =(10 characters)) // I don't know how to phrase this.
  {
     System.out.println("Sorry, you entered the wrong ammount of digits");
  }
  if(num =(10 characters)
  {
     System.out.println("Your Phone number is " + num);
  }
  }
  }

最佳答案

最好的替代方法是使用String而不是StringBuilder并使用String.length()方法来验证用户的输入,并且您的代码也需要进行一些更正。

import java.util.Scanner;
public class Phonenumber
{
public static void main(String[] args)
{
  Scanner input = new Scanner(System.in);
  //StringBuilder num = new StringBuilder(System.in); As we are using String,StringBUilder is not needed

  System.out.println("What is your 10 digit phone number?");
  String num = input.nextLine();
  if(!(num.length()==10)) // Correction: If you use while here and user enters input not having 10 digits it will go to endless loop
  {
     System.out.println("Sorry, you entered the wrong ammount of digits");
  }
  if(num.length()==10) //Here you can use else to make your code more appropriate in case of time complexity(Here Time complexity won't matter but as you seem to be new to java, I think you should check this property)
  {
     System.out.println("Your Phone number is " + num);
  }
  }
  }

关于java - 是否可以使用StringBuilder为输入设置准确的字符数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39052856/

10-10 10:04