java - 如何阻止我的代码多次打印“升序”?
问题描述
我的代码是:
Scanner sc=new Scanner(System.in);
System.out.println("Type in your order(ex.5 7 4 6 8 3 9 2 0 1 - SPACES REQUIRED): ");
String input=sc.nextLine();
for(int i=0;i<input.length(); i++) {
String[] b=input.split(" ");
if(Integer.valueOf(b[i]) < Integer.valueOf(b[i+1])) {
System.out.println("Acsending");
}
else { // When condition is false
System.out.println("Mixed");
}
}
但是当我的输入是 时1 2 3 4 5 6
,输出是:
Ascending
Ascending
Ascending
Ascending
Ascending
而当我的输入是 时1 4 2 5 2
,输出是,
Ascending
Mixed
Ascending
Mixed
如何仅在输入混合或升序时才打印代码?
解决方案
在我之前回答的人(Elliott Frisch)是专业人士,我不知道这条线是做什么的,那些:
Arrays.stream(input.split("\\s+")).mapToInt(Integer::parseInt).toArray();
我自己是初学者,我就是这样做的
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
System.out.println("Type in your order(ex.5 7 4 6 8 3 9 2 0 1 - SPACES REQUIRED): ");
String input=sc.nextLine();
String[] b=input.split(" ");
sc.close(); //Always Close Scanner after user :)
boolean isMixed = false; // Flag
for(int i=0; i < input.length()/2; i++) //input.length() is equal to number + Spaces we don't want spaces
{
//Integer.parseInt(b[i]) converting string to Integer
if(Integer.parseInt(b[i]) < Integer.parseInt(b[i+1]))
{
isMixed = false;
}
else
{
isMixed = true;
}
}
if(isMixed)
{
System.out.println("Mixed");
} else
{
System.out.println("Ascending");
}
}
推荐阅读
- sql - 将一些子字符串从多行转换为新表
- c++ - 如何在 QScintilla 编辑器小部件中取消选择/取消突出显示选定和突出显示的文本?
- android - 期待 Android Espresso 测试中出现异常 - 失败
- visual-studio-code - 我可以在 vscode 中定义替换操作的任务吗?
- java - Java Web Start 弃用
- javascript - 如何在 NodeJS 中将缓冲区编码为 Base64
- python - 如何将 for 循环的输出放入 Python 中的列表?
- ionic-framework - Xcode 命令行构建失败
- apache-kafka - MySQL 的 Debezium 连接器。缺少数据库历史主题
- c# - 将类初始化为 DI 的一部分