Reputation: 1046
I would like to write a program that reads a sequence of integer numbers and outputs true if the sequence is ordered (in asc or desc order), otherwise, false.
The sequence ends with 0. Do not consider this number as a part of the sequence. The sequence always has at least one number (excluding 0).
my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int a;
int b;
boolean asc = true;
boolean dsc = true;
a = read.nextInt();
while (a == 0) {
a = read.nextInt();
}
while (true) {
b = read.nextInt();
if (b == 0) {
break;
}
dsc = dsc && a >= b;
asc = asc && a <= b;
if (asc || dsc == false) {
break;
}
a = b;
}
System.out.println(asc || dsc);
}
}
Test input: 1 2 5 5 2 3 0
Correct output: false
My code output: true
What is wrong with my code?
Upvotes: 0
Views: 367
Reputation: 728
I think the problem is in your if statement if (asc || dsc == false)
which most likely should be if (!asc && !dsc)
.
Result would be this:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int a;
int b;
boolean asc = true;
boolean dsc = true;
a = read.nextInt();
while (a == 0) {
a = read.nextInt();
}
while (true) {
b = read.nextInt();
if (b == 0) {
break;
}
dsc = dsc && a >= b;
asc = asc && a <= b;
if (!asc && !dsc) {
break;
}
a = b;
}
System.out.println(asc || dsc);
}
}
Upvotes: 1
Reputation: 7604
Your if condition before the break
statement is wrong. When you write
if (asc || dsc == false)
it will check if asc
is true
or if dsc
is false
, which means that if the first number's ascending, it will immediately break, and if it isn't, it will break the first time the sequence isn't descending.
What you should put there is !asc && !dsc
, which will get you the output you want. It will only break if both asc
and dsc
are false, and your sequence has no order.
Upvotes: 1