递归作业
我有一个功课问题我可能会过度思考,我需要逆转Hello.
使用递归,以便最终结果没有.
我目前的方法是:
public void foo(){ Scanner scan = new Scanner(system.in); char c = scan.nextChar(); if (c!='.') foo(); System.out.print(c); }
这似乎输出相反,但它仍然有.
。 有人能指出我正确的方向摆脱这段时期吗?
使用'.'
而不是"."
因为你要比较一个char
,而不是一个String
:
public void foo(){ Scanner scan = new Scanner(system.in); char c = scan.nextChar(); if (c != '.') { foo(); System.out.print(c); } }
另请注意,如果它是String
,则需要使用equals
进行比较。 ==
或!=
用于比较基元类型,例如char
。
将打印件放在支架内:
if (c!='.') { foo(); System.out.print(c); }
作为一个char
,它必须是single quotes
, eg : 'A'
if (c!='.') foo(); System.out.print(c); }