gpt4 book ai didi

java - 输入 'y' 后,代码应再次询问选择,但它不会发生

转载 作者:行者123 更新时间:2023-12-02 03:23:16 25 4
gpt4 key购买 nike

import java.util.Scanner;
public class SwitchCase {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

String ch="NULL";
do

{
System.out.println("Enter your choice:");
String str=sc.next();
switch(str)
{

case "Add":
{
System.out.println("Enter 2 nos:");
int a=sc.nextInt();
int b=sc.nextInt();
int c=a+b;
System.out.println("Adiition is:"+c);
break;
}

case "Sub":
{
System.out.println("Enter 2 nos:");
int a1=sc.nextInt();
int a2=sc.nextInt();
int a3=a1-a2;
System.out.println("Sub is:"+a3);
break;

}
case "Multiply":
{
System.out.println("Enter 2 nos:");
int a1=sc.nextInt();
int a2=sc.nextInt();
int a3=a1*a2;
System.out.println("Sub is:"+a3);
break;
}

case "Divide":
{
System.out.println("Enter 2 nos:");
int a1=sc.nextInt();
int a2=sc.nextInt();
int a3=a1/a2;
System.out.println("Sub is:"+a3);
break;
}
case "Fib":
{
System.out.println("Enter the range:");
int n=sc.nextInt();

if (n == 0)
{
System.out.println("0");
}
else if (n == 1)
{
System.out.println("0 1");
}
else
{
System.out.print("0 1 ");
int a = 0;
int b = 1;
for (int i = 1; i < n; i++)
{
int nextNumber = a + b;
System.out.print(nextNumber + " ");
a = b;
b = nextNumber;
}
}
}
}
System.out.println("Do you want to continue? y or n");
ch=sc.next();
} while(ch=="y");

}

}

在 while 循环之后,当用户输入“y”时,它应该询问“你想继续吗?”但同样的情况不会发生。我调试了代码,它运行良好,直到“你想继续吗?” ”但在那之后:

在eclipse中调试时出现源未找到错误

最佳答案

while(ch.equals("y"));

使用等于而不是运算符“==”。

查看Oracle教程:Comparing Strings

关于java - 输入 'y' 后,代码应再次询问选择,但它不会发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39330255/

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