所以這個項目的目的是驗證,如果用戶輸入數字0-9或有小數。它會驗證它是否是數字或字母,但如果用戶沒有放置循環仍然運行的任何東西,就像它是有效的數字一樣。ascii表格計數器與Java不返回爲空虛假
所以,錯誤一:用戶輸入一個有效的浮點數前輸入並且腳本仍然運行有效。
錯誤二:用戶輸入一段時間而不輸入任何數字,腳本仍然運行有效。
package numbers;
/*
* Name: Joshua Trimm
* Date: 9-24-17
* class: CISP 1010
* Project: IsAValidNumber
*/
import java.util.Scanner;
public class IsAValidNumber
{
public static void main(String[] args)
{
//console input scanner
Scanner consoleInput = new Scanner(System.in);
//Prompt user for input
System.out.print("enter a valid number:");
String validat = consoleInput.nextLine();
//define boolean from method
boolean isTrue = NumberIsValid(validat);
//while loop
while(isTrue == true)
{
System.out.println(validat + " is a valid number. Please enter another value:");
validat = consoleInput.nextLine();
isTrue = NumberIsValid(validat);
}
//if it jumps out of the while because it is false run this
System.out.println(validat + " is not a valid number, bye");
consoleInput.close();
}
//setup a boolean method
public static boolean NumberIsValid(String value)
{
//define local variables
int period = 0;
boolean valid = true;
int length = value.length();
//run through the string
//check the numbers
for(int i = 0; i < length; i++)
{
char aChar = value.charAt(i);
// make sure it doesn't start with a space
if((int)aChar == 20)
{
valid =false;
break;
}
// check to make sure its is a int 0-9
else if((int)aChar < 48 || (int)aChar > 57)
{
if((int)aChar == 46)
{
period++;
}
else
{
valid = false;
break;
}
}
//make sure it doesn't have more than one period
if (period > 1)
{
valid = false;
break;
}
}
return valid;
}
}
任何幫助將不勝感激!先謝謝了。
謝謝!錯誤#2修復工作很好。 #1仍然有點麻煩。什麼時候應該檢查輸入isEmpty()?這些循環讓我環繞着自己的大腦! –
這並不重要。我會檢查一下,看看在輸入'int length = value.length()'之後輸入是否爲空。 – Flaom
感謝@Flaom。我會運行它,看看會發生什麼。 –