简体   繁体   English

查找用户输入的连续数量的次数。 使用循环

[英]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. 你们有一个bangin'晚上。

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. 请注意,在使用数组时,它从0开始并转到length - 1索引值为1。 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. 在这句话中,你不接受n个数字。 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. 您可能希望在java中查找和读取数组。

additionally, you are accepting key from user in a do-while loop. 另外,您在do-while循环中接受来自用户的密钥。 you only need to input the key once. 你只需要输入一次密钥。 so you might want to put the code above the do-while loop. 所以你可能想把代码放在do-while循环之上。

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. 如果您在转换为代码时遇到问题,请与我们联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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