使用while循环验证输入

时间:2017-11-24 06:22:02

标签: java

我在计算机科学上做了一些练习,因为当我离开军队时,我想开始学习java的基础知识。我有点卡在这个问题上,我想知道我能不能得到一些帮助。

允许用户输入字符的程序。唯一有效的值是'A','M'和'S'。使用while循环验证输入,以便在用户输入除3个字符之一以外的任何值时,将显示错误消息并提示用户输入其他值。用户最终输入有效数据后,将他们输入的字符打印回屏幕。

2 个答案:

答案 0 :(得分:0)

您可以查看此基本示例

import java.util.Scanner;
public class Read {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean isCheck = true;
        while (isCheck) {
            String str = sc.next();
            switch (str) {
                case "A":
                    System.out.println("A");
                    isCheck = false;
                    break;
                case "M":
                    System.out.println("M");
                    isCheck = false;
                    break;
                case "S":
                    System.out.println("S");
                    isCheck = false;
                    break;
                default:
                    System.out.println("Not Valid : Enter next");
                    isCheck = true;

            }
        }

    }

}

答案 1 :(得分:0)

在循环中读取输入将强制重复读取输入。

<?php
    if(isset($_SERVER['HTTP_ORIGIN']))
    {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    //Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') 
    {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        exit(0);
    }

    $postdata = file_get_contents("php://input");
    if(isset($postdata))
    {
        $request = json_decode($postdata);
        $name = $request->testname;
        $desc = $request->testval;

        if($name != "" && $desc != "")
        {
            $con = mysqli_connect("localhost","root","","ionic_test");

            // Check connection
            if (mysqli_connect_errno())
            {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }
            else
            {
                echo "Name: " .$name;
                echo "Desc: " .$desc;

                $sql  = "INSERT INTO ionictest(testname, testval) VALUES ('$name', '$desc')";
                $stmt = mysqli_query($con, $sql) or die ("MySQL Error:".mysqli_error($con));

                echo "successfully inserted !";
            }
        }
        else 
        {
            echo "Empty name and description parameter!";
        }
    }
    else 
    {
        echo "Not called properly with name and description parameter!";
    }
 ?>