因此,我们得到了为此ScantronGrader编写作业代码的规范,并且规范说我们必须创建此类isValid
来检查属于A,B,C或D的选项的有效性。 (全部大写),我首先尝试了switch
(错误),if-else-if
(错误); do-while
(哦,我知道这是对的,也是错误的)。我首先尝试了for
循环,但该值并未增加。
在最近的演绎中,这是我的问题。 TBH,我什至不知道自己在做什么。
public static boolean isValid(String inputstr)
{
int x = 0;
do
{
switch (inputstr.charAt(x))
{
case 'A':
case 'B':
case 'C':
case 'D':
return true;
default: return false;
x++;
}
} while (x < inputstr.length());
}
}
这个问题是它不能让我增加计数器。现在,我需要这样做,否则,我将如何右移?无论哪种方式,请帮助。
答案 0 :(得分:0)
不确定我是否理解该方法必须执行的操作,但是只有在字符串具有这些字母的情况下,它必须返回true,您才能这样做:
public static boolean isValid(String inputstr)
{
int x = 0;
boolean bool = true;
do
{
if(!(inputstr.charAt(x) == 'A' || inputstr.charAt(x) == 'B' || inputstr.charAt(x) == 'C' || inputstr.charAt(x) == 'D'))
{
bool = false;
}
x++;
}while (x < inputstr.length());
return bool;
}
答案 1 :(得分:0)
好的,所以在这里提出了一些想法之后(谢谢您的帮助),我正在尝试这个似乎可行的想法。请让我知道我是否在做不必要/无用的事情,或者有更有效的方法?
public static boolean isValid(String inputstr) {
int count = 0;
for (int x = 0; x < inputstr.length(); x++) {
switch (inputstr.charAt(x)) {
case 'A':
case 'B':
case 'C':
case 'D':
break;
default: count++;
}
}
if (count == 0) {
return true;
}
else {
return false;
}
}
答案 2 :(得分:-1)
int x = 0;
for(int i; i<inputstr.length(); i++){
if (isValid(inputstr.charAt(i)){
// nothing
} else {
x++;
}
System.out.println(x);
是有效的实现:
public static boolean isValid(Char c) {
switch (c)
{
case 'A':
case 'B':
case 'C':
case 'D':
return true;
}
// default can be ommitted, since this is executed in case it's neither element... which is default
return false;
}
}
ps:请正确学习编程;)找到一位讲师,他将解释其作用
ps2:我不知道为什么你需要右移...