否则If和Do while不能按预期工作 [英] Else If and Do while does not work as intended

查看:106
本文介绍了否则If和Do while不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我最近发生的编译我知道无法编译的程序的事情让我相信我同时遇到了编译器的问题。毫无疑问,由于我在Mac上的WINE中运行它而不是本机应用程序。谢谢你的回复。我将正确测试所有响应并在我使用编译器修复错误时进行所有更改,或者我已将计算机移动到具有工作计算机的计算机。



我相对较新编程和这个网站所以请耐心等待。我的两个我的If语句和一个/我无法解决的错误。



整个程序按预期工作,但下面有两个块。问题是,当我输入字符'y'时,一切都按预期工作,并且(Results =+ Arrays.toString(row))按照我的预期打印。它还继续通过原始For循环并再次启动程序。



但是,当我输入任何其他字符时(即不是'y'或'n'),代码不会打印输入必须是'y'或' n'只是等待另一个输入。即使输入'n',它也不会像我想要的那样循环出来,它只是继续循环而不是继续前进,如果我认为它会。它无限期地执行此操作,不接受除y之外的任何其他输入以继续通过循环,因此我永远不会收到打印否定。



有没有人想过为什么会这样?
虽然不是技术上的功课,但我将其标记为我想知道的,如果可能的话,发生了什么,而不是如何解决它。

  do {
ans = input.next()。charAt(0);
if(!ans.equals('y')||!ans.equals('n')){
System.out.println(输入必须是'y'或'n' );
}
} while(!ans.equals('y')||!ans.equals('n'));

  if(ans.equals('y')){
for(Object [] row:prevResults){
System.out.println(Results =+ Arrays.toString(row) ));
}
} //
else if(ans.equals('n')){
System.out.println(Negative);
//System.exit(0);
}

完整代码如下

  import java.util。*; 

公共类平均值{
public static void main(String [] args){

//声明变量
int course,exam,average = 0;
char ans;
字符串传递;

//创建对象
扫描仪输入=新扫描程序(System.in);
List< Object []> prevResults = new ArrayList< Object []>();

//完整循环
for(int i = 0; i< 5; i ++){

System.out.println(Loop+( ++ i)+满分5);

//课程循环
do {
System.out.println(请输入100分的课程标记);
course = input.nextInt();
if(course> 100){
System.out.println(输入的数字超过100);
}
} while(课程> 100);

//考试循环
do {
System.out.println(请输入100分以上的考试成绩);
exam = input.nextInt();
if(考试> 100){
System.out.println(输入的数字超过100);
}
} while(考试> 100);


平均=(课程+考试)/ 2;

//最终成绩
System.out.println(平均分数为+平均值);

if(平均值> = 50&& course> 40&& exam> 40){
System.out.println(最终成绩通过) );
pass =通过;
}
else {
System.out.println(最终成绩失败);
pass =失败;
}

//添加到数组
prevResults.add(new Object [] {课程标记:+课程,考试标记:+考试,平均: +平均,等级:+通过});


System.out.println(你想看到以前的结果吗?y / n);


//'上一个结果'问题循环
do {
ans = input.next()。charAt(0);
if(!ans.equals('y')||!ans.equals('n')){
System.out.println(输入必须是'y'或'n' );
}
} while(!ans.equals('y')||!ans.equals('n'));


//关闭或数组if语句
if(ans.equals('y')){
for(Object [] row:prevResults){
System.out.println(Results =+ Arrays.toString(row));
}
} //
else if(ans.equals('n')){
System.out.println(Negative);
//System.exit(0);
}
} //结束
} //结束主
} //结束类

编辑2:我已切换计算机并且所有建议的答案确实有效。他们是

  while(ans!='y'&& ans!='n'); 

AND

  while(!(ans.equals('y')|| ans.equals('n'))); 

AND



制作单独的方法Chris Browne建议。



为了其他任何阅读此内容的人的利益,这些解决方案运行得非常好,尽管我没有时间查看Greg Hewgill建议的BufferedReader我很可能会实现它因为它似乎是他所说的更好的选择。

解决方案

首先,代码中出错:

  System.out.println(循环+(​​++ i)+满分5); 

你不应该增加 i 因为它是已经在中为更新语句递增 - 结果导致错误的迭代计数。



接下来,你的不应使用等于来比较 char 值 - 使用 = = 。当你使用等于时,由于自动装箱,最终导致大约 characterObject.equals(anotherCharacterObject),对象属于键入 java.lang.Character 。只需使用例如 ans =='y'而不是。



最后,正如大家所指出的那样,你应该改写你的 - as as:

  do {
ans = input.next()。charAt(0);
if(ans!='y'&& ans!='n'){
System.out.println(输入必须是'y'或'n');
}
} while(ans!='y'&& ans!='n');

甚至还有单独的条件检查方法(感谢Chris Browne)。


EDIT: Recent happenings of me compiling a program I know could not compile lead me to believe I am simultaneously having an issue with my compiler. No doubt due to my running it in WINE on mac as opposed to a native application. Thank you for your responses. I will properly test out all responses and make all changes when I have fixed said error with compiler or I have moved computers to one with a working one.

I am relatively new to programming and also this website so please bear with me. I am getting an error with my two of my If statements and one do/while that I am unable to resolve.

The entire program works as intended but two blocks which are below. The problem is that when I enter the character 'y', everything works as intended and the ("Results =" + Arrays.toString(row)) prints as I expected it to. It also proceeds to continue through the original For loop and start the program again.

However, when I enter any other character, (i.e not 'y' or 'n') the code does not print "Input must be either 'y' or 'n'" and just waits for another input. Even when 'n' is entered, it does not follow out of the the loop as I wanted, it just continues to loop and not proceed to the else if I had thought it would. It does this indefinitely, not accepting any other input than 'y' to continue passed the loop so I can never receive the print "negative".

Does anyone have any thoughts as to why this is happening? While not technically homework, I tagged it as such as I want to know, if possible, what is happening as opposed to just how to fix it.

        do {
            ans = input.next().charAt(0);
                if (!ans.equals('y')  ||  !ans.equals('n')) {
                    System.out.println ("Input must be either 'y' or 'n'");
                }
        } while (!ans.equals('y')  ||  !ans.equals('n'));

and

if (ans.equals('y')) {
            for (Object[] row : prevResults) {
                    System.out.println("Results = " + Arrays.toString(row));
            }
        } //
        else if (ans.equals('n')) {
            System.out.println("Negative");
            //System.exit(0); 
        }

Full code is as below

import java.util.*;

public class Averages {
    public static void main (String [] args) {

        //declare variables
        int course, exam, average = 0;
        char ans;
        String pass;

        //creating objects
        Scanner input =  new Scanner(System.in);
        List<Object[]> prevResults = new ArrayList<Object[]>();

        //full loop
        for (int i = 0; i < 5; i++ ) {

            System.out.println ("Loop " + (++i) + " out of 5");

            //Course loop
            do {
            System.out.println ("Please enter a course mark out of 100");
            course = input.nextInt();
                if (course > 100) {
                    System.out.println ("Number entered is over 100");
                }
            } while (course > 100);

            //Exam loop
            do {
            System.out.println ("Please enter an exam mark out of 100");
            exam = input.nextInt();
                if (exam > 100) {
                    System.out.println ("Number entered is over 100");
                }
            } while (exam > 100);


            average = (course + exam)/2;

            // Final Grade
            System.out.println ("The average mark is " + average);

            if ( average >= 50 && course > 40 && exam > 40)  {
                System.out.println ("The final grade is pass");
                pass = "Pass";
            }
            else {
                System.out.println ("The final grade is fail");
                pass = "Fail";
            }

            //add to array
            prevResults.add(new Object[] { "Course mark: " + course, "Exam mark: " + exam,"Average: " + average, "Grade: " + pass});


            System.out.println ("Would you like to see previous results? y/n");


            //'Previous results' question loop
            do {
                ans = input.next().charAt(0);
                    if (!ans.equals('y')  ||  !ans.equals('n')) {
                        System.out.println ("Input must be either 'y' or 'n'");
                    }
            } while (!ans.equals('y')  ||  !ans.equals('n'));


            // Close or Array if statement
            if (ans.equals('y')) {
                for (Object[] row : prevResults) {
                        System.out.println("Results = " + Arrays.toString(row));
                }
            } //
            else if (ans.equals('n')) {
                System.out.println("Negative");
                //System.exit(0); 
            }
        }// end for 
    }//end main
}//end class

EDIT 2: I have switch computers and all the suggested answers to indeed work. They being

while (ans != 'y' && ans != 'n');

AND

while (!(ans.equals('y')  ||  ans.equals('n')));

AND

Making a separate method as suggested by Chris Browne.

For the benefit of anyone else who reads this, these solutions work wonderfully although I have not had time to look at the BufferedReader suggested by Greg Hewgill I will most likely implement it because it seems like a better option from what he has stated.

解决方案

First, an error in your code:

System.out.println ("Loop " + (++i) + " out of 5");

You should not increment i as it is already incremented in your for update statement - you are getting the wrong iteration count as a result.

Next, your should not use equals to compare char values - use == instead. When you use equals, a lot of unnecessary things happen due to the auto-boxing, that ultimately result in roughly characterObject.equals(anotherCharacterObject), objects being of type java.lang.Character. Just use e.g. ans == 'y' instead.

Last, as folks have pointed out, you should rewrite your do-while as:

do {
    ans = input.next().charAt(0);
    if (ans != 'y' && ans != 'n') {
        System.out.println ("Input must be either 'y' or 'n'");
    }
} while (ans != 'y' && ans != 'n');

or even have a separate method for the condition check (thanks to Chris Browne).

这篇关于否则If和Do while不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆