当 Do While 循环终止且不执行扫描函数时

huangapple 未分类评论45阅读模式
英文:

Do While loop terminates and doesn't execute scanner function

问题

以下是我的“Do-While”循环代码。我无法弄清楚为什么在甚至还没有输入变量“redo”的值之前,它就已经终止了,而这是在do {}部分的末尾。它在打印“您是否想再次执行此操作”的部分之后立即终止。

import java.util.Scanner;
public class AlgWorkbench0402 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String redo;
        
        do {
            System.out.println("输入两个整数并得到它们的和。");
            int val1, val2;
            val1 = Integer.valueOf(scanner.nextInt());
            val2 = Integer.valueOf(scanner.nextInt());
            
            System.out.println(val1 + val2);
            System.out.println("您是否想再次执行此操作?[y/n]");
            
            redo = scanner.nextLine();
            
        }
        while (redo.equals("y") || redo.equals("Y"));
    }
}
英文:

Below is my code for a "Do-While" loop. I can't figure out why it's terminating before I even get to enter in the value for my variable "redo" at the end of the do {} section. It terminates right after printing the "would you like to do this again" part.

import java.util.Scanner;
public class AlgWorkbench0402 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		String redo;
		
		do {
			System.out.println("Enter in two integers and get the sum.");
			int val1, val2;
			val1 = Integer.valueOf(scanner.nextInt());
			val2 = Integer.valueOf(scanner.nextInt());
			
			System.out.println(val1 + val2);
			System.out.println("Would you like to do this again? [y/n]");
			
			redo = scanner.nextLine();
			
		}
		while (redo == "y" || redo == "Y");
	}
}

huangapple
  • 本文由 发表于 2020年4月7日 01:35:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/61065582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定