2016-09-05 30 views
0
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”是由用户输入后,就应该问:“你要继续”,但同样不会发生。我调试了代码,它运行良好,直到“你想继续吗?”但在那之后:输入“Y”的代码又应该选择要求后,但它不会发生

源没有发现错误出现,在eclipse调试时

+0

@ piet.t不错,但是这个代码甚至不应该从我能看到的东西中编译。 '找不到源代码......“这听起来像您的IDE中的代码与您正在运行的代码不同步。 –

+0

这里可能存在另一个隐藏的错误。 'sc.nextInt()'会从STDIN中提取整数,但是会在“你要继续吗?”之后通过'sc.next()'调用立即吃掉尾随的换行符。题。 – Phylogenesis

+0

@Phylogenesis这是错误的。 'next()'不读取分隔符。你的意思是'nextLine()'。 – Tom

回答

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

使用equals代替运算符 “==”。

检查Oracle教程:Comparing Strings

+1

请勿将明显的副本发布回答。这种问题已经被要求数千次,并且投票结束,因为重复是处理它的正确方法。 – Tom

0

在您比较ch=="y" while条件。比较字符串时,应该使用equals方法,如"y".equals(ch)。等号运算符将测试两个值是否具有相同的参考值,显然,它们不具有相同的参考值。

+2

请勿将明显的副本发布。这种问题已经被要求数千次,并且投票结束,因为重复是处理它的正确方法。 – Tom

相关问题