我需要以任意順序測試連續數字。我的程序似乎工作正常,當我按照1,2,3
或8,3,3
的順序輸入數字時,但我需要以任何順序讀取數字,例如3,2,4
應該返回true。輸入數字的連續數可以任意順序
例子應該返回true
:
(1,2,3)
(3,2,4)
(-10,-8,-9)
例子應該返回false
:
(3,5,7)
(1,2,2)
(7,7,9)
。
import java.util.*;
public class Consecutive {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();
System.out.println("The numbers (" + numbers + ") is '" + consecutive(numbers) + "'");
}
private static boolean consecutive(String str) {
char c = str.charAt(0);
for (int cc = 1; cc < str.length(); cc++)
if ((c + 1) != str.charAt(cc))
return false;
else
c++;
return true;
}
}
你是什麼意思?有序,以便每個以下數字更大?有序,所以每個都更小? –
您需要先在連續方法中將字符串排序爲整數數組,然後繼續。 – mbroshi
排序字符串?或者你的意思是要對字符列表進行排序... – vikingsteve