Java:比较2个数字,去掉较低的一个



我正在做家庭作业,我遇到了一个问题,我不知道如何对脑子里的东西进行编码。输入的数字数量未知。

INPUT(示例(:1 2 2 3 4 10 4 5 6 7 10 11 11 5 6 8 9 10

OUTPUT:输出必须是一行中不同数字的最大数量(定义见下一行(。我说得再好不过了,但你以后可能会明白我的意思。我会把不同号码的号码称为NODN

ROW定义:只要下一个输入不低于上一个输入,就考虑1行。在示例中,我们有4行:

1 2 3 4 10,
4,
3 4 5 6 7 10 11 11 11,
5 6 7 8 9 10

期望的输出将是7,因为第三行将具有最大数量的不同数字。

我只能使用Scanner、int和boolean类型。代码的第一部分(至少我相信是这样(得到第一行的NODN,第二部分得到第二行的数字。我想做的是比较这两个数字,去掉较低的一个,然后继续比较,直到它到达输入的末尾。我不知道如何保持较高的NODN值并不断进行比较。非常感谢。

代码:

while (sc.hasNextInt()) {
preLast = last;
last = sc.nextInt();
if (last > preLast) {
numberOfDiffNumbers++;
}
if (last < preLast) {
while (sc.hasNextInt()) {
preLast = last;
last = sc.nextInt();
if (last > preLast) {
numberOfDiffNumbers2++;
}
if (last < preLast) {
break;
}
}
}

这里有一个使用4个int变量的想法:

// hold the highest NODN value here. The output of the program 
int result = 0;
// hold the NODN value of the current line here 
int numberOfIntsInTheLine = 0 
/* holds the initializing  value of a line.
* Can hold the value of the previous number given by  the scanner.
* Use this to check the current number against the previous number */
int initOrMinimumValueForALine= 0;
while(sc.hasNextInt() {
int currentNumber = sc.nextInt();
// if Current number is greater than the previous number, we keep counting 
if(currentNumber > initValueForALine ) {
//TODO Increment numberOfIntsInTheLine;
//TODO Assign currentNumber to initOrMinimumValueForALine
} 
/** if Current number is smaller than the previous number, check NODN to see if it's the highest and stop processing the line **/
if(currentNumber < minimumNumberForALine) { 
if(numberOfIntsInTheLine > result) { 
//TODO assign current NODN to highest NODN;
//TODO break the loop; // to stop processing the current line><br/>
}
}          
}

让我们思考一下如何处理我们得到的每个新数字。也许我们还希望变量存储到目前为止最高的NODN是多少,当前行中的数字数量是多少,以及我们读取的最后一个数字是多少。现在,当我们读取每个数字时,以下任何一个都是可能的:

  • 我们正在读取第一个数字
  • 下一个数字大于上一个数字
  • 下一个数字与上一个数字相同
  • 下一个数字小于上一个数字
  • 我们读完了数字

我试图在不提供太多代码的情况下提供一些帮助,但对于上面的每一种情况,请考虑如何修改这3个变量中的每一个(迄今为止最高的NODN、当前行的长度、以前的数字(

好的,您需要一个提示,所以我将向您展示肯定很好的代码。。。如果填写正确。

Scanner sc = new Scanner(line);
int maxElts = 0;
int elts = 0;
int last = Integer.MIN_VALUE;
// iterate over all of the integers
while (sc.hasNextInt()) {
int x = sc.nextInt();
if (x > last) {
// TODO something to elts
} else if (x < last) {
// we're going to have to start over
if (elts > maxElts) {
// TODO but if the number of elts was higher ...
}
elts = ?; // TODO so how many elts are in the new row we've just found?
}
// we don't do anything for x == last - or should we?
last = x;
}
// OK, but 
if (elts > maxElts) {
// TODO but if the number of elts was higher ...
}
System.out.println(maxElts);

要带走的一些东西:

  • 想想你想循环什么,在这种情况下,输入整数最有意义
  • 想想你想记住什么,什么时候想记住
  • 思考如何初始化变量,以及它们应该如何改变状态以及何时改变
  • 您可能需要在循环之前或之后重复一些操作或采取特殊操作
  • 不要测试两次,如果x > last,那么x < last当然不必测试

最新更新