gpt4 book ai didi

Java for 循环错误

转载 作者:行者123 更新时间:2023-11-30 09:35:17 30 4
gpt4 key购买 nike

我正在尝试使用 for 语句获取 sortValues[] 数组的用户输入(输入字符 1、输入字符 2 等)。

但是,当我执行此操作时,程序将不允许我输入字符 2,而是直接跳到字符 3,如下所示。

enter image description here

如何解决?代码包含在下面。

谢谢!

static public void s_1d_char () {
int counter=0;
int x=0;
c.print("How many characters? ");
counter = readInt();

char[] sortValues = new char[counter+1];

for (x=1;x<=counter;x++) {
System.out.println("Enter character "+(x)+":");
sortValues[x] = readChar();
}
}

readChar 实现(来自库):

public synchronized char readChar ()
{
char result, ch;

if (ungotChar != EMPTY_BUFFER)
{
result = (char) ungotChar;
ungotChar = EMPTY_BUFFER;
return (result);
}

if (lineBufferHead != lineBufferTail)
{
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
return (result);
}

startRow = currentRow;
startCol = currentCol;
if (currentRow > maxRow)
{
startRow++;
currentCol = 1;
}

// Turn cursor on if necessary
consoleCanvas.setCursorVisible (true);

// Wait for a character to be entered
while (true)
{
ch = getChar ();

if (ch == '\n')
{
clearToEOL = false;
if (echoOn)
print ("\n");
clearToEOL = true;
lineBuffer [lineBufferHead] = '\n';
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
break;
}
if (ch == '\b')
{
if (lineBufferHead == lineBufferTail)
{
consoleCanvas.invertScreen ();
}
else
{
int chToErase;

lineBufferHead = (lineBufferHead + lineBuffer.length - 1) % lineBuffer.length;
chToErase = lineBuffer [lineBufferHead];
if (echoOn)
{
if (chToErase != '\t')
{
erasePreviousChar ();
}
else
{
int cnt;
eraseLineOfInput ();
cnt = lineBufferTail;
while (cnt != lineBufferHead)
{
print (lineBuffer [cnt]);
cnt = (cnt + 1) % lineBuffer.length;
}
}
}
}
} // if backspace
else if (ch == '\025')
{
if (echoOn)
{
eraseLineOfInput ();
}
lineBufferHead = lineBufferTail;
}
else
{
if (echoOn)
{
print (ch);
}
lineBuffer [lineBufferHead] = ch;
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
}
} // while

result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;

// Turn cursor on if necessary
consoleCanvas.setCursorVisible (false);

return (result);
}

最佳答案

我建议使用扫描仪获取用户输入:

import java.util.Scanner;

// ...
int counter = 0;

System.out.println("How many characters?");
Scanner keyboard = new Scanner(System.in);
counter = keyboard.nextInt();

char[] sortValues = new char[counter+1];

// Start your index variable off at 0
for (int x = 0; x < counter; x++) {
System.out.println("Enter character "+(x)+":");
keyboard = new Scanner(System.in);
String line = keyboard.nextLine();
sortValues[x] = line.charAt(0);
}

这将捕获该行的第一个字符。如果用户输入多个字符,程序将只读取第一个字符。另外,考虑到数组是从 0 开始索引的,您真的应该从 0 开始索引变量 x

关于Java for 循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11422451/

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