简体   繁体   中英

Finding how many times a number has, consecutively, been entered by the user. Using loops

I'll admit it, this is indeed a school project. Here's the question itself, since I feel its too complex to be paraphrased:

Write a JAVA program that prompts the user to enter a positive integer and store it in a 
variable named n.
You may assume without error checking that the value n is positive.  
The user is then prompted to enter n number of integers.  After the n integers have been 
entered, the program then prompts the user to enter another single integer to be stored in
a variable named key. The program must now determine and output the maximum number of 
times the value key was entered consecutively. (If the key was never entered, output 0. If
it was entered, but never twice in a row, output 1.) 

Sorry about the wall of text, but there you have it. Now, I don't come begging for answers. I have some code I've been rigorously working on, but I cannot figure out the consecutive part. Here it is :

import java.util.Scanner;
public class Consecutive {
    public static void main(String[] args) {

  Scanner kbd = new Scanner(System.in);
  System.out.print("Enter a positive integer: ");
     String n = kbd.nextLine();

  System.out.print("Now, enter "+n+" integer(s), of any kind: ");    
     int any = kbd.nextInt();

  do {                                    
    System.out.println("Now enter one integer, the key: ");
      int key = kbd.nextInt();
    for (int i = 0; i < n.length(); i++) {
                } // Havent figured out this part yet, or if its even needed.
      } while (any == n.length());



}
}

Its not the greatest stuff, I know. Any help at all would be much appreciated. You have yourselves a bangin' evening.

From what your teacher and/or book has written, it looks like you are required to use arrays, or a form of them, to successfully determine how many times the key was entered consecutively. Here is what I would do with arrays:

import java.util.Scanner;
public class Consecutive 
{
    public static void main(String[] args) 
    {
        // Variable declaration
        int count = 0; 
        Scanner kbd = new Scanner(System.in);

        System.out.print("Enter a positive integer: ");
        int n = kbd.nextInt();

        System.out.print("Now, enter " + n + " integer(s), of any kind: ");    
        int[] ints = new int[n]; // Declares an array with length "n" to store the numbers

        for (int i = 0; i < n; i++)
        {
            if (kbd.hasNextInt()) // Checks to make sure they are entering integer.
                ints[i] = kbd.nextInt();
            else
            {
                i--; // Keeps increment the same unless you have a correct input
                kbd.next(); // Clears the scanner so you can check the next thing entered.
            }
        }

        System.out.println("Now enter one integer, the key: ");
        int key = kbd.nextInt();

        for (int i = 0; i < ints.length; i++)
        {
            if (ints[i] == key) // Checks to see what value in array is equal to key
                count++; // If it's equal add to count.
        }
        System.out.println("The key was entered " + count + " times."); // Display how many times key in array
    }
}

To work with arrays, you first must allocate memory to the array, using the form:

type[] variableName = new type[optionalLength];

To assign values to the array, you simply type in the index value (which you can think of a slot in array which holds a value), an example being:

int[] oneTwoThree = new int[3];
oneTwoThree[0] = 1;
oneTwoThree[1] = 2;
oneTwoThree[2] = 3;

Notice that while using arrays, it starts at 0 and goes to length - 1 for the index value. Another way to declare values in array is something of the form:

int[] oneTwoThree = new int[3];
for (int i = 0; i < oneTwoThree.length; i++)
    oneTwoThree[i] = i + 1; // i goes from 0 to 2, and we are setting oneTwoThree from one to three.

System.out.print("Now, enter "+n+" integer(s), of any kind: ");
int any = kbd.nextInt();

In this sentence, you are not accepting n numbers. you are just accepting one number for user. Arrays are a way you are store multiple values of same data type together. you might want to lookup and read about arrays in java.

additionally, you are accepting key from user in a do-while loop. you only need to input the key once. so you might want to put the code above the do-while loop.

Lastly, have a new variable that keeps the count of the consecutive times key was encountered. initialize it to zero and now in a loop try to track how many times you encounter the key consecutively.

Dwell on the specification for a little longer, you've looped over the user entering a key, but the key should only be entered once after all the numbers have been entered right? Rethink what process actually requires repetition and then ask again if you get stuck :)

A good way to tackle these problems when you first start coding is to write an algorithm as 'psuedocode'. This means writing it as kind-of-English that allows you to focus on the solution without having to worry about the language syntax.

For example, here's some psuedocode for working out the longest consecutive series of a particular item in a list. Hopefully it'll give you something to get started

set longestChain to 0
set currentChain to 0
for all the items in the list
    if item equals key 
        increment currentChain
        if currentChain is greater than longestChain
            set longestChain to currentChain
    otherwise
        set currentChain to 0

Essentially it looks at each item and increments a counter if it equals the key. As soon as an item does not equal the key it sets the counter back to zero. Meanwhile it keeps account of the longest series so far.

Let me know if you have trouble converting to code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM