Java跳过while语句并直接结束

时间:2017-04-21 19:54:54

标签: java

这是我第一个完成计算机编程的学期,我们的教授在课堂上完全赐给我们。但我设法几乎完成了课堂作业,但出于某种原因,我的同时声明被忽略了。

import java.util.Scanner;
import java.text.DecimalFormat;

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

            DecimalFormat f = new DecimalFormat("##.00");

            float votesForPolly; 
            float votesForErnest; 
            float totalPolly = 0; 
            float totalErnest = 0; 
            String response; 
            int precinctsforpolly = 0; 
            int precinctsforernest = 0;
            int precinctsties = 0;

            Scanner scan = new Scanner(System.in);
            System.out.println ();      
            System.out.println ("Election Day Vote Counting Program");
            System.out.println ();


            do
            {   
                System.out.println("Do you wish to enter more votes? Enter y:n");
                response = scan.next();
                //this is where it skips from here*********
                while (response == "y")
                {
                    System.out.println("Enter votes for Polly:");
                    votesForPolly = scan.nextInt();
                    System.out.println("Enter votes for Ernest:");
                    votesForErnest = scan.nextInt();

                    totalPolly = totalPolly + votesForPolly;
                    totalErnest = totalErnest +  votesForErnest;

                    System.out.println("Do you wish to add precincts? Enter y:n");
                    response = scan.next();
                    if (response =="y")
                    {   
                        System.out.println("How many precincts voted for Polly: ");
                        precinctsforpolly = scan.nextInt();
                        System.out.println("How many precincts votes for Ernest: ");
                        precinctsforernest = scan.nextInt();
                        System.out.println("How many were ties: ");
                        precinctsties = scan.nextInt(); 
                    }
                }
            }
            while (response == "n");
            //to here*********************************************
            System.out.println("Final Tally");
            System.out.println("Polly received:\t " + totalPolly + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
            System.out.println("Ernest received: " + totalErnest + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
            System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");

        }
}

1 个答案:

答案 0 :(得分:3)

字符串有效地指向Java中的值,而不是值本身。尝试使用

while (response.equals("y"))

而不是

while (response == "y")

在前一种情况下,您告诉运行时实际比较这些值。后一种情况告诉运行时要比较指针,这些指针实际上可能不匹配。