我目前正在编写一个程序(java),询问用户的班级时间表,以及每个班级有多少学分。学分的唯一有效答案应该是1,2,3或4.我如何检查以确保这些是唯一有效的答案?如果他们输入无效金额,我希望它循环并提示他们完全相同的问题。这是我到目前为止所拥有的。
//Jake Petersen
import java.util.Scanner;
public class test{
//I promise not to make all methods static in CS1
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length; i++){
System.out.println("Please enter how many credits " + courseArray[i] + " is:");
creditArray[i] = scan.nextInt();
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
答案 0 :(得分:4)
你必须这样做。
var query = Comment.find({ "author": userId });
query.select("post").populate("post");
query.exec(function(err, results){
console.log(results);
var posts = results.map(function (r) { return r.post; });
console.log(posts);
});
此部分可以插入到您的代码中。比它再问一次
答案 1 :(得分:0)
作为替代方案,您可以简单地将增量拉出循环,如果输入有效则只增加i
,如下所示:
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
答案 2 :(得分:0)
您可以使用while循环和布尔变量来检查状态
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length; i++) {
boolean isValid = true;
while(isValid)
{
System.out.println("Please enter how many credits " + courseArray[i] + " is:");
int buffer = scan.nextInt();
if(buffer == 1|| buffer == 2||buffer == 3||buffer==4)
{
isValid = false;
creditArray[i] = buffer;
}
}
第二种方法是使用像这样的do-while-statement:
boolean isValid = true;
do{
System.out.println("Please enter how many credits " + courseArray[i] + " is:");
int buffer = scan.nextInt();
if(buffer == 1|| buffer == 2||buffer == 3||buffer==4)
{
a=false;
}
}while(a);