我的Java程序采用用户输入的一系列数字,并应确定该字符串是否是一系列最多10个连续序列号,或者数字序列是否包含相同的数字。
输入的数字由短划线字符分隔。该程序应显示“正确的连续序列”,“错误的连续序列”,“找到一对数字”,“对找不到数字“和/或”输入无效“。
我正在努力进行输入验证。我一直在研究代码几个小时。如果我输入“ n ”使其停止运行,迭代循环仍会运行,当它应该接受的唯一内容是“ y ”或“ Y ”。此外,如果我在尝试输入“w”时应该说“无效输入”,则代码会中断。
最后,如果没有先输入,则不会检测到一对。例如, 3-3-4-5 被检测为具有一对的序列,但它也不包括它是连续的。如果我输入 3-4-5-5-6 ,它将无法检测到该对。我无法弄清楚它为什么会这样做。请帮忙。我的代码如下所示。
import java.util.Scanner;
public class JavaApplication12 {
/**
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char ch = 'y';
//LOOP TO CONTINUOUSLY TAKE INPUT
while(ch != 'n' || ch != 'N'){
System.out.println("Enter a sequence of numbers");
String num = sc.next();
// WE WILL TAKE STRING INPUT SO WE WILL SPLIT IT WITH DELIMITER
String arr[] = num.split("-");
if(arr.length < 10){
int arrint[] = new int[arr.length];
for(int i=0;i< arr.length;i++){
arrint[i] = Integer.parseInt(arr[i]);
}
// PRESCRIBED CONDITOIONS AND USE OF 2 FUNCTIONS
if(arrint[0] == arrint[1]){
System.out.println("Pair Found");
}else if(arrint[0] == (arrint[1] + 1)){
new func().decreasing(arrint);
}else if(arrint[0] == (arrint[1] - 1)){
new func().increasing(arrint);
}
}else{
System.out.println("Invalid Input");
}
//CODE THAT ASKS USER TO CONTINUE OR NOT
System.out.println("Want to enter more (Y/n)");
ch = sc.next().charAt(0);
}
}
}
// CLASS THAT CONTAINS LOGIC OF FUNCITONS
class func{
public void increasing(int[] arr){
int flag = 1;
for(int i=0;i<arr.length - 1;i++){
if(!(arr[i] == (arr[i+1] - 1))){
flag = 0;
break;
}else if(arr[i] == (arr[i+1])){
flag = 2;
break;
}
}
if(flag == 0){
System.out.println("Incorrect consecutive sequence");
}else if(flag == 1){
System.out.println("Correct consecutive sequence");
}else if(flag == 2){
System.out.println("Pair of numbers found");
}
}
public void decreasing(int[] arr){
int flag = 1;
for(int i=0;i<arr.length - 1;i++){
if(!(arr[i] == (arr[i+1] + 1))){
flag = 0;
break;
}else if(arr[i] == (arr[i+1])){
flag = 2;
break;
}
}
if(flag == 0){
System.out.println("Incorrect consecutive sequence");
}else if(flag == 1){
System.out.println("Correct consecutive sequence");
}else if(flag == 2){
System.out.println("Pair of numbers found");
}
}
}
答案 0 :(得分:1)
以下语句将始终评估为true,字符如何同时等于两个不同的字符?
size_t position = 0;
while((position = sentence.find(replacedString, position)) != sentence.npos) {
sentence.replace(position, strLength, stringToReplace);
position += stringToReplace.length();
}
将其更改为while (ch != 'n' || ch != 'N')