gpt4 book ai didi

java - 在某些输入后停止用户输入?

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:56 25 4
gpt4 key购买 nike

我正在解决一个非常简单的Java问题,我需要在输入某个用户值后停止接收数据。输入值后,用户仍然可以输入数据,但输入值后,输出不应包含该值或该值后面的任何数据。另外,我试图将负数条目排除在计数之外,但无济于事。这是我的代码。任何帮助,将不胜感激!谢谢!

import java.util.Scanner;

public class Sample
{
public static void main (String[] args)
{
System.out.println("Please input any number, up to 10 entries. "
+ "Enter -1 to exit: ");
Scanner read = new Scanner(System.in);
int[] input_array = new int[10];
int numOfEntries = 0;
for(int i = 0; i < input_array.length; i++)
{
input_array[i] = read.nextInt();
numOfEntries++;
//only positive numbers
if(input_array[i] >= 100 || input_array[i] < 0)
{
if(input_array[i] == 77) //certain value
{
//entries before 77 is entered become the new array
numOfEntries = i;
int[] new_array = new int[numOfEntries];
for (int j = 0; j < numOfEntries; j++)
{
new_array[j] = input_array[i];
}
System.out.print(new_array[numOfEntries] + " ");
}
if(input_array[i] == -1) //exit loop
{
break;
}
System.out.println("Please enter a positive
number that is less than 100.");
}
}

//final result
System.out.println("Your entries are: ");
for (int i = 0; i < numOfEntries; i++)
{
System.out.print(input_array[i] + " ");
}

最佳答案

您应该像这样检查以确保一切都正确地通过条件

//all this goes inside the for loop
String input = read.nextInt();
if (input == -1)
break;
if (input > 0)//is it negative?
{
if (input < 100)//is it greater than 100?
{
if (input == 77)//is it 77?
{
//your code
}
else//this will run when all conditions are passed
input_array[i] = input;
}
}

关于java - 在某些输入后停止用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649890/

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