java - 处理布尔数组的 int 输入时遇到问题
问题描述
在我的程序中,我要求用户输入多个整数来表示书中包含的章节,例如“1 0 1 0 0 1”来表示阅读的第 1、3、6 章或“1 1 1 0 1”到表示 1-3、5。我不知道如何将这种输入处理成布尔数组,然后打印语句。
这是我到目前为止的代码:
import java.util.Scanner;
public class WhichChaptersToRead {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int chapters = -1;
String chapterOut = " ";
boolean[] chpSelect = new boolean[15];
boolean rightInput = false;
System.out.println("Enter the chapters to read: ");
while(!rightInput){
if(keyboard.hasNextInt()){
chapters = keyboard.nextInt();
if(chapters > 1 || chapters < 0){
System.out.println("Out of scope of the inclusion or exclusion of chapters");
System.out.println("Enter either 0 or 1");
}else{
chapterOut = formatChapter(chapters, chpSelect);
}
}else{
System.out.println("Wrong type of input.");
System.out.println("Enter integers 0 or 1");
}
}
}
public static String formatChapter(int chapters, boolean[] chpSelect){
}
}
感谢所有的帮助。
解决方案
我重新实现了你的逻辑。抱歉,我想不出更简单的方法。当然,有多种方法可以解决这个问题。
第一步,要求阅读章节。
第二步将不为零或不为一的所有内容替换为空(即仅允许0
并且1
-不验证)。
第三步创建 aboolean[]
以将零和一值存储到boolean[]
(这是您要求的)。
第四步计算分配了多少章,以便我们可以使用正确的复数形式进行输出。
第五步,使用 aStringJoiner
构建输出章节列表。
喜欢,
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the chapters to read: ");
String line = keyboard.nextLine();
line = line.replaceAll("[^01]", "");
int selectedCount = 0;
boolean[] selected = new boolean[line.length()];
for (int i = 0; i < line.length(); i++) {
selected[i] = line.charAt(i) == '1';
if (selected[i]) {
selectedCount++;
}
}
if (selectedCount == 0) {
System.out.println("There are no assigned chapters.");
return;
} else if (selectedCount == 1) {
System.out.print("Read chapter ");
} else {
System.out.print("Read chapters ");
}
StringJoiner sj = new StringJoiner(", ");
for (int i = 0; i < selected.length; i++) {
if (selected[i]) {
sj.add(String.valueOf(i + 1));
}
}
System.out.println(sj);
推荐阅读
- c# - 在 Azure IoTEdge 的模块中启动长时间运行方法的最佳方式是什么?
- image-processing - UWP:将图像裁剪为圆形
- flutter - Flutter - StatefulWidget 和路由
- javascript - 当有人点击我想要播放声音时
- mysql - 是否可以将经典数据库与一个视图列混合?
- angular - Angular mat-drawer-container cdkScrollable 退订问题
- sql - 从 PostgreSQL 获取数据的正确方法是什么?
- javascript - 香草javascript轮播不滑动
- c# - 使用 Powershell 关闭 IE 中的活动选项卡
- java - 使用正确参数查找对象的代码出错