Java 编写具有char输入和char输出的方法
我正在尝试创建一种方法,将一个互补的DNA碱基分配给另一个碱基 以下是我目前的情况:Java 编写具有char输入和char输出的方法,java,Java,我正在尝试创建一种方法,将一个互补的DNA碱基分配给另一个碱基 以下是我目前的情况: public class DnaTest { public static void main(String[] args){ } public static boolean aGoodBase (char c) { boolean aBase; if (c == 'A' || c == 'G' || c == 'C' || c == 'T')
public class DnaTest {
public static void main(String[] args){
}
public static boolean aGoodBase (char c) {
boolean aBase;
if (c == 'A' || c == 'G' || c == 'C' || c == 'T')
{
aBase = true;
}
else
{
aBase = false;
}
System.out.println(aBase);
return aBase;
}
public static char baseComplement (char c){
boolean anotherBase = isGoodBase(c);
if (anotherBase)
{
if (isGoodBase('A'))
{
c = 'T';
}
else if (isGoodBase('T'))
{
c = 'A';
}
else if (isGoodBase('G'))
{
c = 'C';
}
else if (isGoodBase('C'))
{
c = 'G';
}
System.out.println(c);
return c;
}
else
{
System.out.println(c);
return c;
}
}
}
第二种方法应首先使用第一种方法验证输入的字符是否为有效基(CG或T),然后分配其互补基(如果基无效,则应仅打印出相同的字符,例如输入Z、输出Z)
使用此代码,我在输入“A”时得到以下输出:
true
true
true
T
但是如果我输入另一个基,我会得到完全相同的输出
当我输入一个无效的基,如“z”,我得到:
false
false
z
有人能帮我吗?在确定互补基的代码中,您正在写:
if (isGoodBase('A')) {
c = 'T';
}
if (c == 'A') {
c = 'T';
}
当你应该写作时:
if (isGoodBase('A')) {
c = 'T';
}
if (c == 'A') {
c = 'T';
}
您已经检查了basec
是否为正确的base(因为我们的情况是另一个base为true),因此无需再次检查
您可以使用以下工具更轻松地重写:
在确定互补基的代码中,您正在编写:
if (isGoodBase('A')) {
c = 'T';
}
if (c == 'A') {
c = 'T';
}
当你应该写作时:
if (isGoodBase('A')) {
c = 'T';
}
if (c == 'A') {
c = 'T';
}
您已经检查了basec
是否为正确的base(因为我们的情况是另一个base为true),因此无需再次检查
您可以使用以下工具更轻松地重写:
更少的代码-更少的出错机会
public static char baseComplement (char c){
int index = "ATGC".indexOf( c );
if( index >= 0 ){
return "TACG".charAt( index );
} else {
return c;
}
}
强烈建议对文本使用最终的静态字符串。代码越少,出错的可能性越小
public static char baseComplement (char c){
int index = "ATGC".indexOf( c );
if( index >= 0 ){
return "TACG".charAt( index );
} else {
return c;
}
}
强烈建议对文本使用最终静态字符串。提示:switch语句将是解决此问题的更简单的方法。接下来,请注意您正在调用
if(isGoodBase('A'))
等-这些调用根本不依赖于c
的值…顺便说一句:aGoodBase-isGoodBase谢谢您的回答!我不允许使用switch语句,不幸的是,我将根据您刚才告诉我的内容更改代码并编辑我的帖子。非常感谢。禁止使用不易出错的构造是一种令人遗憾的教育技术。提示:switch语句将是解决此问题的更简单的方法。接下来,请注意您正在调用if(isGoodBase('A'))
等-这些调用根本不依赖于c
的值…顺便说一句:aGoodBase-isGoodBase谢谢您的回答!我不允许使用switch语句,不幸的是,我将根据您刚才告诉我的内容更改代码并编辑我的帖子。非常感谢。禁止使用不易出错的构造是一种令人遗憾的教育技术。我不能使用switch语句,但我已经在if语句中应用了更改,现在打印出了正确的基。但我还是会把布尔值打印两次。。。这是为什么?@Jayzpeer在你的帖子中,你缺少main
方法中的代码。也许您正在调用它里面的isGoodBase
?我不能使用switch语句,但我已经在if语句中应用了更改,现在打印出了正确的基。但我还是会把布尔值打印两次。。。这是为什么?@Jayzpeer在你的帖子中,你缺少main
方法中的代码。也许你正在里面调用isGoodBase
?