gpt4 book ai didi

java - 循环和逻辑语句

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

我有这个类(class)所需的程序,他们要求我完成它的方式让我很困惑,因为我无法输出正确的答案。需要的是一系列输入,其中包含一系列“x”、“X”和“r”,它们依次输出声音。如果输入包含不是“x”、“X”或“r”的字符,则必须输出类似于“请输入有效输入”的内容。在大多数情况下,我已经把所有东西都放下了,但我无法找到一种方法来正确显示无效的输入字符串。

import java.util.Scanner; 
public class String2Beat { //main class
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("To play a drum song please enter a series of x's and r's.");
System.out.println("Use an Uppercase X for the base drum, ");
System.out.println("Use a Lowercase x for the snare drum, ");
System.out.println("Or use a Uppercase R for a rest:");
String drums = scan.nextLine();

for (int j = 0; j < 3; j++){
for (int i = 0; i < drums.length(); i++){
if (drums.charAt(i) != 'x' && drums.charAt(i) != 'X' && drums.charAt(i) != 'r'){
System.out.println("not a valid string input");
}
else {
if (drums.charAt(i) == 'X'){
System.out.println("Now playing a Bass Drum. " + drums.charAt(i));
playBass();
}
else if(drums.charAt(i) == 'x'){
System.out.println("Now playing a Snare Drum. " + drums.charAt(i));
playSnare();
}
else if(drums.charAt(i) == 'r'){
System.out.println("Now playing a Rest. " + drums.charAt(i));
playRest();
}
}

}

}

scan.close();
}

最佳答案

您需要做的是在播放声音之前确定字符串是否包含无效输入。您的程序可能应该如下所示:

import java.util.Scanner; 
public class String2Beat { //main class
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("To play a drum song please enter a series of x's and r's.");
System.out.println("Use an Uppercase X for the base drum, ");
System.out.println("Use a Lowercase x for the snare drum, ");
System.out.println("Or use a Uppercase R for a rest:");
String drums = scan.nextLine();

boolean test = false;

for (int i = 0; i < drums.length(); i++)
{
if (drums.charAt(i) != 'X' || drums.charAt(i) != 'x' || drums.charAt(i) != 'R')
test = true;
}

if (!test)
{
for (int j = 0; j < 3; j++)
{
for (int i = 0; i < drums.length(); i++)
{
if (drums.charAt(i) == 'X')
{
System.out.println("Now playing a Bass Drum. " + drums.charAt(i));
playBass();
}
else if(drums.charAt(i) == 'x')
{
System.out.println("Now playing a Snare Drum. " + drums.charAt(i));
playSnare();
}
else
{
System.out.println("Now playing a Rest. " + drums.charAt(i));
playRest();
}
}
}
}
}
else
{
System.out.println("not a valid string input");
}

scan.close();
}

关于java - 循环和逻辑语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33745695/

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