如何在完成后打印所有数字 [英] How do I print all the numbers after it's done

查看:96
本文介绍了如何在完成后打印所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我正确显示了数字,但我不知道如何显示所有数字,而且我无法显示重复的数字。这是问题。



使用一维数组来解决以下程序。写一个

应用程序,输入六个数字[将数字保存在数组中]。这些数字可以是20到200之间的b $ b,包括20和200。输入数字时,仅在数字为
不是已输入数字的副本时显示数字。提供所有

六个数字不同的最坏情况。在用户输入每个新值后显示输入的完整唯一值集。



输入数字:5 //提示

数字必须在20到200之间//如果有必要显示警告信息
输入数字:21 //再次提示

21 //显示数组中保留的数字

输入数字:32 //再次提示

21 32 //每次在新号码后显示所有输入的数字

添加

输入数字:23

21 32 23

输入数字:23

23已输入//如果输入重复的数字则显示消息

输入数字:33

21 32 23 33



我尝试过:



这是我到目前为止的代码

My problem is I got the numbers displayed correctly, but I don't know how to display all of them, and I can't display duplicate numbers. This is the problem.

Use a one-dimensional array to solve the following program. Write an
application that inputs six numbers [Keep the numbers in an array]. The numbers can be
between 20 and 200, inclusive. When a number is entered, display the number only if it
is not a duplicate of a number already entered. Provide for the worst case in which all
six numbers are different. Display the complete set of unique values input after the user enters each new value.

Enter number: 5 //prompt
Number must be between 20 and 200 //display warning message if it is necessary
Enter number: 21 // prompt again
21 //display the number kept in the array
Enter number: 32 // prompt again
21 32 //display all entered numbers in the array each time after a new number is
added
Enter number: 23
21 32 23
Enter number: 23
23 has already been entered //display message if a duplicate number is entered
Enter number: 33
21 32 23 33

What I have tried:

Here is my code so far

import java.util.Scanner; //program uses Scanner

public class Duplicate {
	public static void main (String [] args) {
		
		//declare an array with 5 elements
		int myArray[] = new int[6];
		//int counter = 0;
		//boolean duplicate = false;
		
		Scanner input = new Scanner(System.in);
		while(counter < myArray.length){
			System.out.print("Enter an integer between 20 and 200: ");
			int number = input.nextInt();
						
			if (number >= 20 && number <= 200)
			{
				++counter;
				myArray[counter] = number;
				System.out.printf("%d%n", myArray[counter]);
			}
		else{
			System.out.println("Error: You did not enter a number between 20 and 200");
			}
		}
	}
}

推荐答案

首先初始化数组每个项目包含一个超出有效数字范围的值。在这种情况下, -1 将是一个合理的选择。每次输入新数字时,您需要检查它是否在有效范围内,但是它还没有在您的数组中。完成后,将其添加到数组的下一个空元素并打印数组的有效数字。
Start by initialising the array so that each item contains a value that is outside the range of valid numbers. In this case -1 would be a reasonable choice. Each time a new number is entered you need to check that it is in the valid range, but also that it is not already in your array. Once you have done that, then add it to the next 'empty' element of the array and print the valid numbers of the array.


这篇关于如何在完成后打印所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆