[英]How to use a method with a char input and a boolean output?
謝謝大家的回答! 另一個問題:我如何打印出布爾值? System.out.println(goodBase)似乎不起作用
public class Dna {
public static void main(String[] args){
aBase('A');
}
public static boolean aBase (char c) {
char [] charArray = { 'A', 'G', 'C', 'T' };
boolean goodBase;
if (c == 'A' || c == 'G' || c == 'C' || c == 'T')
{
return true;
}
else
{
return false;
}
}
}
謝謝 !
如果您在正確的環境中使用該代碼,那么該代碼對我有用。 我已附上以下完整的功能示例:
public class Main {
// create a Test Method
public static boolean test(char c) {
if (c == 'A' || c == 'G' || c == 'C' || c == 'T') {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// create some sample data
String sample = "AGCTEDHI";
// test
for (int i = 0; i < sample.length(); i++) {
char current = sample.charAt(i);
System.out.println(current + " is " + test(current));
}
}
}
輸出:
A is true
G is true
C is true
T is true
E is false
D is false
H is false
I is false
我認為是這樣的:
char [] charArray = { 'A', 'G', 'C', 'T' };
if (base == charArray[0] || base == charArray[1] ||
base == charArray[2] || base == charArray[3])
return true; // a good base
return false;
首先,要在if
語句中檢查的aGoodBase
方法中沒有聲明名為char
變量。
其次,這是真正的交易,因為char
是Java中的保留關鍵字(例如byte
, int
, long
, public
, strictfp
等),所以這樣的變量永遠不會存在,並且只能用於將變量聲明為a原始char
類型。
這回答了為什么DnaTest
不編譯。
現在,讓我們考慮一個可能的解決方案:
public class DnaTest {
private final static char [] baseArray = {'A', 'C', 'G', 'T'};
// checks whether String s only contains the right base elements or not
public static boolean aGoodBase(String s){
String s1 = s.toUpperCase(); // just ensuring case insensitive checks
for (int i=0; i<s1.length(); i++) {
char check = s1.charAt(i);
if (baseArray[0] != check &&
baseArray[1] != check &&
baseArray[2] != check &&
baseArray[3] != check) {
// at least one char of s is not in baseArray
return false;
}
}
return true;
}
public static void main(String[] args) {
// should be true
System.out.println("Does GATTACA have aGoodBase? " + aGoodBase("GATTACA"));
// should be false
System.out.println("Does MORROW have aGoodBase? " + aGoodBase("MORROW"));
// should be true, the check on the base is case insensitive
System.out.println("Does GaTTaca have aGoodBase? " + aGoodBase("GaTTaca"));
// should be false
System.out.println("Does GATMOR have aGoodBase? " + aGoodBase("GATMOR"));
}
}
輸出:
Does GATTACA have aGoodBase? true
Does MORROW have aGoodBase? false
Does GaTTaca have aGoodBase? true
Does GATMOR have aGoodBase? false
現在,如果s僅包含baseArray數組中聲明的四個基本元素的組合,則aGoodBase方法采用String並返回true。 即使基本元素不是用大寫字母,我也可以自由地返回true(例如在主體的第三個示例:GaTTaca中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.