【问题标题】:Possible without String?没有字符串可以吗?
【发布时间】:2019-05-18 07:44:47
【问题描述】:

没有字符串我无法解决这个任务(还不知道):

“我的程序询问用户是否想看笑脸。如果他回答'Y',他会得到一个“:)”,其他输入将是一个“:(”。使用条件运算符。”

我的解决方案(带字符串):

System.out.println("Do you want to see a smiley");
answer=scan.findWithinHorizon(".",0).charAt(0);

string=(answer=='Y')?: ":)" : ":(";  //works like that but I need it without string
System.out.println(string);

btw:条件运算符是不是经常用到?

感谢您的帮助 如果有任何进一步的建议,请告诉我。

【问题讨论】:

  • 不能使用字符串是什么意思?
  • "顺便说一句:条件运算符经常使用吗?"当然是。 “可能没有字符串”是什么意思?
  • 喜欢System.out.println((answer=='Y')?: ":)" : ":(")?是的,经常使用条件句。
  • 您的条件运算符不需要返回字符串 - 而只是 char 值')' 或'('
  • @Serge 谢谢你工作正常

标签: java string boolean conditional-operator


【解决方案1】:

我不知道我是否理解你,但你可以试试:

if(answer=='Y'){
System.out.println(":)");
}
else{
System.out.println(":(");
}

是的,例如条件运算符:if/else 是编程中的基本内容之一。

【讨论】:

  • 这就是我通常的做法。但我应该在没有 if else 操作的情况下做到这一点。抱歉没有提到!
【解决方案2】:

你的意思是没有String 变量吗?然后是讨厌的oneliner:

System.out.println("Do you want to see a smiley");
System.out.println(scan.findWithinHorizon(".",0).charAt(0)=='Y' ? ":)" : ":(" );

如果您的意思是不使用任何类型的字符串(甚至不使用“”),您可以单独冷打印每个字符。这不需要String,但确实很烦人且没有必要。

编辑:因为请求,这里是这个版本:

System.out.print('D');
System.out.print('o');
....
System.out.print('y');
System.out.print('\n');

if (scan.findWithinHorizon(".",0) == 'Y') {
     System.out.print(':');
     System.out.print(')');
     System.out.print('\n');
} else {
     ....
}

【讨论】:

  • 谢谢。好吧,我现在用一本书来学习,它还没有告诉我字符串的作用。所以我必须把它打印出来,否则我猜。
  • 顺便说一句,每个字符单独是什么意思?你能帮我打个代码吗?^^
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多