英文:
Checking for boolean in Java switch case
问题
以下是翻译好的内容:
所以我有一个嵌套在switch语句中的switch语句,我正在输入一个字符串,我的情况是使用.contains方法,如下面的代码所示:
intcheck: switch(line){
case line.contains("0"):
case line.contains("1"):
case line.contains("2"):
case line.contains("3"):
case line.contains("4"):
case line.contains("5"):
case line.contains("6"):
case line.contains("7"):
case line.contains("8"):
case line.contains("9"):
break intcheck;
default:
names.put(br.readline(), 0);
}
是否可以使用switch语句实现类似的功能,或者是否必须使用if语句?还有没有更简单的方法来检查字符串是否包含数字,这样做可以吗?
英文:
So I have a switch case into switch I am inputting a string and my cases are .contains as shown in my code below:
intcheck: switch(line){
case line.contains("0"):
case line.contains("1"):
case line.contains("2"):
case line.contains("3"):
case line.contains("4"):
case line.contains("5"):
case line.contains("6"):
case line.contains("7"):
case line.contains("8"):
case line.contains("9"):
break intcheck;
default:
names.put(br.readline(),0);
}
Is it possible to achieve something similar to this using a switch statement or will I have to use
if statements. Also is there an easier way to check if a string contains a digit or is that OK?
答案1
得分: 0
虽然还有更好的方法来处理,如果你坚持使用 switch-case
结构,请尝试这样写:
OptionalInt containedNumber = OptionalInt.empty();
Intcheck: for (var i = 0; i < 10; ++i) {
switch (i) {
case 0:
if (line.contains("0")) containedNumber = OptionalInt.of(0);
break Intcheck;
case 1:
if (line.contains("1")) containedNumber = OptionalInt.of(1);
break Intcheck;
// ...
case 9:
if (line.contains("9")) containedNumber = OptionalInt.of(9);
break Intcheck;
default:
continue IntCheck;
}
}
if (containedNumber.isEmpty()) names.put(br.readline(), 0);
不使用 switch-case
:
OptionalInt containedNumber = OptionalInt.empty();
for (var i = 0; (i < 10) && containedNumber.isEmpty(); ++i) {
if (line.contains(Integer.toString(i))) containedNumber = OptionalInt.of(i);
}
if (containedNumber.isEmpty()) names.put(br.readline(), 0);
英文:
Although it could be done better in a different way, if you insist in a switch-case
construct, try this:
OptionalInt containedNumber = OptionalInt.empty();
Intcheck: for( var i = 0; i < 10; ++i )
{
switch( i )
{
case 0: if( line.contains( "0" ) containedNumber = OptionalInt.of( 0 ); break Intcheck;
case 1: if( line.contains( "1" ) containedNumber = OptionalInt.of( 1 ); break Intcheck;
…
case 9: if( line.contains( "9" ) containedNumber = OptionalInt.of( 9 ); break Intcheck;
default:
continue IntCheck;
}
}
if( containedNumber.isEmpty() ) names.put( br.readline(), 0 )
Without the switch-case
:
OptionalInt containedNumber = OptionalInt.empty();
for( var i = 0; (i < 10) && containedNumber.isEmpty(); ++i )
{
if( line.contains( Integer.toString( i ) ) containedNumber = OptionalInt.of( i );
}
if( containedNumber.isEmpty() ) names.put( br.readline(), 0 )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论