我尝试检查数组以查看该数字是否已列出,如果用户碰巧输入了两次数字,则该数字应放置在最新的顶部,而其他所有内容都应向下移动。简而言之,给定数组 [4, 5, 6, 7, 9],如果用户输入 7,则应将其更改为 [7, 4, 5, 6, 9]。
//Array Created
int intArray[] = new int[5];
//Number of values in the array
int count = 0;
//Value user enters
int userInput = 0;
//Receive user inputs
Scanner in = new Scanner(System.in);
//First Prompt
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
//Keep asking for number if invalid
while((userInput < 0) || (userInput > 10)){
System.out.println("Invalid number. Must be between 1 - 10\n");
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
}
intArray[count] = userInput;
count++;
while(userInput != 0){
//Keeps Track of the numbers inputed
System.out.println("There is currently " + count + " On The Table.");
for(int i = 0; i < count; i++){
System.out.print(intArray[i] + " ");
}
System.out.print("\n\n");
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
//Don't Allow numbers bigger than 10 or less than 1
while(userInput < 0 || userInput > 10){
System.out.println("Invalid number.\n");
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
}
if(count == intArray.length){
int tempPrev;
for(int i = (intArray.length - 1); i > 0; i--){
//Store the previous value
tempPrev = intArray[i - 1];
//Assign current index to what was in previous
intArray[i] = tempPrev;
}
intArray[0] = userInput;
count = intArray.length;
} else {
intArray[count] = userInput;
count++;
}
}
System.out.println("The end.");
} }
我将为数组提供一个解决方案,我假设如果用户指定了一个新项目,它将到达数组的头部并将所有内容拉到右侧,最旧的项目会从数组中掉出:
int index = intArray.indexOf(input);
if (index < 0) {
index = intArray.length; //we default to the last item that would disappear
for (int i = index; i > 0; i--) {
intArray[i] = intArray[i - 1];
}
intArray[0] = input;
让我们从以下事实开始:您的数组需要具有唯一性,因此您需要一个集合。
使用标准库可以找到的最佳(快速)实现是
LinkedHashSet<Integer>
。
如果我们分析一下它的文档,我们可以看到默认情况下它保留插入顺序,这非常适合您的情况,但是,我们还注意到,如果元素存在,它会忽略重新插入:
这个链表定义了迭代顺序,也就是中的顺序 哪些元素被插入到集合中(插入顺序)。注意 如果将元素重新插入到中,则插入顺序不受影响 放。 (如果调用 s.add(e),则元素 e 会重新插入到集合 s 中 当 s.contains(e) 在紧接之前返回 true 时 调用。)
要解决此问题,您可以创建一个实用函数,首先尝试从集合中删除要插入的数字,然后再次重新插入,从而更改插入顺序。
例如
final var set = new LinkedHashSet<Integer>();
...
static void addFirst(Set<Integer> set, int val) {
set.remove(val);
set.add(val);
}
此时,您可以获取其迭代器并读取您最需要的设置值。
注意: 由于只有当读取沿迭代器的方向或者与插入相比较少时,这才是有效的,因此,如果您必须经常反向迭代,那么您最好使用
LinkedList<Integer>
直接做和remove()
和add()
一样的小游戏。
那是因为,不幸的是,尽管该集合是双向链接的,但您可以反向滚动它的唯一方法如下:
final var list = new LinkedList<>(set);
final var it = list.descendingIterator();
while(it.hasNext()) {
int item = it.next();
// do something
}
保持现有方案,这是实现这一目标的一种方法。阅读代码中的注释:
可运行代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class AddNewButDeleteDuplicate_Demo {
// System related newline character sequence. Could be used anywhere.
public static final String LS = System.lineSeparator();
// Open a keyboard input stream. Could be used anywhere.
public static final Scanner userInput = new Scanner(System.in);
// Application Entry Point:
public static void main(String[] args) {
// App started this way to avoid the need for statics:
new AddNewButDeleteDuplicate_Demo().startApp(args);
}
private void startApp(String[] args) {
// This code can create an int[] array of any size:
int[] intArray; // Declare our int[] array
int count = 1; // Counter used for 'number of entries' display:
// Inform of upcoming prompt:
System.out.println("Enter integer numbers (1 to 10) to add to Array" + LS
+ "or enter 's' at any time to stop.");
/* List Interface of Integer to hold all integer values supplied
by User.This List is later converted to an int[] Array. List
is used because it can grow dynamically whereas Arrays can not.
This then allows the User to enter as many elements as desired
which the rules specify 10 elements max since we can only enter
values from 1 to 10. */
List<Integer> intList = new ArrayList<>();
// To hold the current value supplied by User:
String inputValue = "";
// Repeatable User Entry Prompt with a Stop mechanism and entry Validation:
while (inputValue.isEmpty()) {
// Prompt:
System.out.print("Entry #" + count + ": -> ");
// Get User Entry:
inputValue = userInput.nextLine().trim();
// Is 'Stop' desired?
if (inputValue.equalsIgnoreCase("s")) {
// Yes...Inform and exit `while` loop
System.out.println("Done Creating Array!");
break; // Exit `while` loop.
}
/* Validate User Entry. If the entry IS NOT a string representation
of a unsigned integer value from 1 to 10 then indicate as invalid
and allow the User to try again. */
if (!inputValue.matches("\\d+") || Integer.parseInt(inputValue) < 1 ||
Integer.parseInt(inputValue) > 10) {
System.out.println(">> Invalid Entry (" + inputValue + ")! Try again... <<" + LS);
inputValue = ""; // Empty variable to ensure re-loop.
continue; // Jump to top of loop:
}
/* If we made it to this point, then the User supplied value is
valid. Convert the User supplied string numerical value to
int data type. */
int val = Integer.parseInt(inputValue);
/* For demo purposes, display the Current List before checking
for duplicates: */
System.out.println("List Previous: -> " + intList);
// Check for duplicate...
/* If List is not empty and the int value of the User supplied
number IS currently contained within the List then remove the
duplicate value already contained within the List and insert
the new (same) value to the beginning of the List at index 0. */
if (!intList.isEmpty() && intList.contains(val)) {
int idx = intList.indexOf(val);
/* If the duplicate is already located at index 0 of the List
then there is no point doing any modification to the List
since this is where we would place the new value anyways. */
if (idx != 0) {
intList.remove(idx);
intList.add(0, val);
// Inform of duplicate entry:
System.out.println(">> Duplicate Entry (" + inputValue + ")! "
+ "Old value removed at index " + idx + " and New value inserted "
+ "into index 0. <<" + LS);
}
}
// Otherwise, just add the int value to the List:
else {
intList.add(val);
}
/* For demo purposes, display the Current List after checking
for duplicates: */
System.out.println("List Current: -> " + intList);
inputValue = ""; // Empty variable to ensure re-loop.
count++; // Increment User entry count:
}
// Convert the List to an int[] Array using Streams:
intArray = intList.stream().mapToInt(d -> d).toArray();
// Display int[] Array:
System.out.println("The intArray[] Array: -> " + Arrays.toString(intArray));
}
}