gpt4 book ai didi

Java stdin 不提示程序运行

转载 作者:行者123 更新时间:2023-12-01 08:51:13 26 4
gpt4 key购买 nike

我正在研究合并排序算法,目前正在尝试测试它是否有效。

它应该通过标准输入进行控制,输入格式为:

数组长度元素值(用“”分隔)

但是,输入时:

3
17 10 3

什么也没发生,然后按回车键,就让我进入控制台中的下一行。

我没有收到任何错误消息(除非我输入了错误的输入),因此我很难弄清楚为什么不提示脚本使用给定的输入运行。

(代码复制如下)

package merge;

import java.io.*;
import java.util.*;

public class MergeSort
{
// This method takes two sorted arrays of integers as input parameters
// and it should return one sorted array of integers.
public int[] merge(int[] A1, int[] A2) {
int[] C = new int[A1.length + A2.length];
int i = 0, j = 0, k = 0;
while (i < A1.length && j < A2.length)
C[k++] = A1[i] < A2[j] ? A1[i++] : A2[j++];

while (i < A1.length)
C[k++] = A1[i++];

while (j < A2.length)
C[k++] = A2[j++];

return C;
}

// This method takes an array of integers as input parameter,
// and it should then return the integers sorted
// in ascending order using the MergeSort algorithm.
private int[] sort(int[] numbers) {
//pointers
int i = 0, j = 0, k = 0;
// reference values
int half = numbers.length / 2;
int[] sorted = new int[numbers.length];

if (numbers.length <= 1){
return numbers;
}

//left part of 'numbers'
int[] left = new int[half];
int[] right;

//right part of 'numbers'
if (numbers.length % 2 != 0){
right = new int[half+1];
j = half + 1;
}
else{
right = new int[half];
j = half;
}
//fills out left half of array with values from input array
while (i < half)
left[i] = numbers[i];
i++;

//fills out right half of array with values from input array
while (j < numbers.length)
right[j] = numbers[k];
j++; k++;

left = sort(left);
right = sort(right);

merge(left,right);

return sorted;
}

// ##################################################
// # Stdin part. #
// ##################################################

public static void main(String[] args) throws IOException {
new MergeSort().run();
}

private void run() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int[] numbers = readIntArray(in);

numbers = sort(numbers);
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}

private int[] readIntArray(BufferedReader in) throws IOException {
int length = Integer.parseInt(in.readLine());
int[] array = new int[length];
StringTokenizer st = new StringTokenizer(in.readLine());

for (int i = 0; i < length; i++) {
array[i] = Integer.parseInt(st.nextToken());
}
return array;
}
}

最佳答案

您调用 readLine() 两次,导致尝试读取标准输入上的两行。

关于Java stdin 不提示程序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42393272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com