因此,我试图简单地检查我的变量是否作为字符串输入,我想要if语句通过而不是未处理的异常......
这是我的代码:
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
$query = "INSERT INTO floradtable (Category, Brand, Price) VALUES";
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
$query .= "('".$results['Category']."','".$results['Brand']."','".$results['Price']."'),";
echo "<div style='position:relative; font-size:18px; width:500px;'><span style='font-size:14px'>".$results['Category']."</span> - <strong>".$results['Brand']."</strong> - ".$results['Description']." - <span style='color:red;'>$".$results['Price']."</span> ".$results['Size']."</div>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
$query = substr($query, 0, -1);//to remove the trailing comma
$mysqli->query($query);
}
那我在这里做错了什么?每次我输入一个字符串,我都没有进入if语句,只是一次崩溃!
答案 0 :(得分:3)
代码中的问题是传递给TryParse
的值与传递给Convert.ToInt32
的值没有关联。您应该阅读该值,然后使用相同的值调用TryParse
:
Console.WriteLine("Enter an integer:");
var s = Console.ReadLine();
int i;
if (int.TryParse(s, out i)) {
Console.WriteLine("You entered an integer");
} else {
Console.WriteLine("You did not enter an integer");
}
如果您想继续阅读,直到最终用户输入有效的int
,请添加循环,如下所示:
int i;
do {
Console.WriteLine("Enter an integer:");
var s = Console.ReadLine();
} while (!int.TryParse(s, out i));
答案 1 :(得分:1)
我认为你应该这样做
Console.Write("Input: ");
int i;
bool success = int.TryParse(Console.ReadLine(), out i); //Getting the input and checking it
if (!success)
{
Console.WriteLine("Enter Integer!");
}
else
{
Console.WriteLine("Output: ", i);
}
在您的代码中,您在else语句中获取了值,如果您的输入无法解析为int
,则会抛出异常。