Is there anyway to shorten this Java code by validating name and weight using only one do…while?

huangapple go评论76阅读模式
英文:

Is there anyway to shorten this Java code by validating name and weight using only one do...while?

问题

以下是您要翻译的内容:

有没有办法在一个 do while 循环中同时验证姓名(String)和重量(double)?如何添加可选的正则表达式,例如 [./ ],除了 [a-zA-Z]+ 之外?

do {
    System.out.print("姓名:");
    name = input.nextLine();
    if (Pattern.matches("[a-zA-Z]+", name)) {
        isValid = true;
    } else {
        System.out.println("无效输入\n请重试\n");
        isValid = false;
    }
} while (!(isValid));

do {
    System.out.print("身高(厘米):");
    input.nextLine();

    if (input.hasNextDouble()) {
        height = input.nextDouble();
        if (height > 5 && height <= 500) {
            isValid = true;
        } else {
            System.out.println("无效输入\n请重试\n");
            isValid = false;
        }
    } else {
        System.out.println("无效输入\n请重试\n");
        isValid = false;
    }
} while (!(isValid));
英文:

Is there any way to validate name(String) and weight(double) in only one do while?
How to add optional regex such as [./ ] besides [a-zA-Z]+ ?

do {
                System.out.print(&quot;Name: &quot;);
                name = input.nextLine();
                if (Pattern.matches(&quot;[a-zA-Z]+&quot;, name)) {

                isValid = true;
            } else {
                System.out.println(&quot;Invalid input\nPlease try again\n&quot;);

                isValid = false;

            }
        } while (!(isValid));
do {
            System.out.print(&quot;Height(cm): &quot;);
            input.nextLine();

            if (input.hasNextDouble()) {
                height = input.nextDouble();
                if (height &gt; 5 &amp;&amp; height &lt;= 500) {
                    isValid = true;
                } else {
                    System.out.println(&quot;Invalid input\nPlease try again\n&quot;);
                    isValid = false;
                }
            } else {
                System.out.println(&quot;Invalid input\nPlease try again\n&quot;);
                isValid = false;
            }
        } while (!(isValid));

答案1

得分: 1

你可以将可选的正则表达式 [./ ] 添加到相同的模式中,用 | 分隔开。可以像这样在单个 do-while 中执行验证:

import java.util.regex.*;
import java.util.*;

public class StackOverflow
{    
 public static void main(String[] args) 
 {
  Boolean isNameValid = false, isHeightValid = false;
  String name = null; double height = 0;
  Scanner input = new Scanner(System.in);
  Pattern pattern = Pattern.compile("[a-zA-Z]+|[./ ]");
 
  do
  {  
   if(!isNameValid)
   {
     System.out.print("Name: ");
     name = input.nextLine();
     Matcher match = pattern.matcher(name);
  	 if (match.find()) 
 		isNameValid = true;
     else
     {
 		System.out.println("Invalid input\nPlease try again\n");
   		isNameValid = false;
 	 }
   }
   if(isNameValid && !isHeightValid)    
   {
	  System.out.print("Height(cm): ");
 	  if (input.hasNextDouble())
 	  {
         height = input.nextDouble();
   	 	 if (height > 5 && height <= 500)
   			isHeightValid = true;
  		 else 
  		 {
 	        System.out.println("Invalid input\nPlease try again\n");
     		isHeightValid = false;
  		 }
  	  } 
  	  else
	  {
 	     System.out.println("Invalid input\nPlease try again\n");
   	     isHeightValid = false;
 	  }
   }
  }while(!(isNameValid)||!(isHeightValid));
  
  input.close();
 }
}
英文:

You can add the optional regular expression [./ ] into the same pattern separated by |. Validation in a single do-while can be performed like this:

import java.util.regex.*;
import java.util.*;

public class StackOverflow
{    
 public static void main(String[] args) 
 {
  Boolean isNameValid = false, isHeightValid = false;
  String name = null; double height = 0;
  Scanner input = new Scanner(System.in);
  Pattern pattern = Pattern.compile(&quot;[a-zA-Z]+|[./ ]&quot;);
 
  do
  {  
   if(!isNameValid)
   {
     System.out.print(&quot;Name: &quot;);
     name = input.nextLine();
     Matcher match = pattern.matcher(name);
  	 if (match.find()) 
 		isNameValid = true;
     else
     {
 		System.out.println(&quot;Invalid input\nPlease try again\n&quot;);
   		isNameValid = false;
 	 }
   }
   if(isNameValid &amp;&amp; !isHeightValid)    
   {
	  System.out.print(&quot;Height(cm): &quot;);
 	  if (input.hasNextDouble())
 	  {
         height = input.nextDouble();
   	 	 if (height &gt; 5 &amp;&amp; height &lt;= 500)
   			isHeightValid = true;
  		 else 
  		 {
 	        System.out.println(&quot;Invalid input\nPlease try again\n&quot;);
     		isHeightValid = false;
  		 }
  	  } 
  	  else
	  {
 	     System.out.println(&quot;Invalid input\nPlease try again\n&quot;);
   	     isHeightValid = false;
 	  }
   }
  }while(!(isNameValid)||!(isHeightValid));
  
  input.close();
 }
}

答案2

得分: 0

你可以这样做:

validName = False
validWeight = False
while True:
    if not validName:
        # 获取并验证姓名
        # 当找到正确的姓名时,将 validName 设置为 True
        pass
    if validName and not validWeight:
        # 获取并验证重量
        pass
    if validName and validWeight:
        break

如果有多于两个这样的验证步骤,你可以将每个读取和验证的过程封装在一个函数中。

英文:

You can do something like this:

Boolean validName = false, validWeight = false;
do {
if(!validName) {
//get and validate weight
// when found the correct name; set validName to true
}
if(validName &amp;&amp; !validWeight) {
//get and validate weight
}
}while(validName &amp;&amp; validWeight);

If there are more than two such validations you can wrap each read-validate in a function.

huangapple
  • 本文由 发表于 2020年10月11日 17:19:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64302417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定