проблема с циклом do-while. успешно скомпилирован с использованием BlueJ

1

Каждый идеальный куб (например, 8, 27, 216 и т.д.) Может быть выражен как сумма ряда последовательных нечетных чисел. Это факт, что такой ряд будет содержать ровно "n" последовательных нечетных чисел, где "n" - кубический корень данного куба.

 For example: 1) 8=3+5= 2^3 (2 odd numbers)
              2) 125=21+23+25+27+29= 5^3 (5 odd numbers)
              3) 1000=91+93+95+97+99+101+103+105+107+109= 10^3 (10 odd numbers)

Следующий код генерирует ряд последовательных нечетных чисел, сумма которых равна совершенному кубу, который берется как вход (переменное имя 'куб'). ПРОБЛЕМА - В данном коде нет никаких синтаксических ошибок, и он запускается только один раз, несмотря на цикл do-while, который гарантирует, что пользователь может попробовать разные кубы, указав Yes/No (Y/N), когда будет задано.

import java.util.*;

class CUBE {   

    void main() {              
        /*gives a series of consecutive odd numbers                                          
        whose sum is equal to the input value.  
        input is a cube of a number less than 1000*/

        int i,odd,t,sum,cube,n; String c="y"; 
        Scanner sc=new Scanner(System.in);        

        do {
            i=1;
            odd=1;
            t=2;
            sum=0;
            System.out.println("\nEnter the cube");
            cube=sc.nextInt(); //input is stored in 'cube'
            n=cubeRoot(cube);  /*'n' is the cube root of 'cube'. If 'cube'  
                                     is not a perfect cube then n=0*/
            while(i<=n) {
                sum+=odd;  //consecutive odd numbers are are added in sum    
                if(sum==cube) //loop stops if sum=cube
                {
                    break;
                }
                else if (i==n && sum!=cube) {
                    i=1; //counter goes back to 1
                    sum=0;
                    odd=i+t; //odd becomes the next odd number just after 1 and then the one after that
                    t+=2;
                }
                else {
                    i++; 
                    odd+=2;
                }
            }
            if (n!=0) { //if 'cube' is a perfect cube then n will never be 0
                System.out.print("\n"+cube+" = ");
                 for(i=odd-2*(n-1);i<=odd;i+=2)
           {
               if(i==odd)  
                 System.out.print(i+"\n\n");
               else
                 System.out.print(i + " + ");
           }
                System.out.println("\nTry again? (Y/N)\n");                                   
                c=sc.nextLine();
            } 
        }
        while(c.equals("y")||c.equals("Y"));
        //if c is "y" then loop should run again but it doesnt
    }

    int cubeRoot(int cube)  {                    
        /*returns the cube root of 
                    cube and returns 0 if its 
                    invalid */

        int i;
        for(i=1;i<=1000;i++) //n sholud be less than 1000
        {
            if(i*i*i==cube) //if i^3 = cube then n=i
                return i;
        }
        System.out.println("\nINVALID INPUT.");//prints if cube is not a perfect cube 
        return 0;
    }
} 
  • 0
    Является ли вся ваша программа этим опубликованным кодом?
Теги:

1 ответ

0
Лучший ответ

просто добавьте новый сканер внутри цикла while, и он работает:

                   System.out.println("\nTry again? (Y/N)\n"); 
                   Scanner sc2=new Scanner(System.in);                                 
                   c=sc2.nextLine();

ВВОД, ВЫВОД:

c is : y

Enter the cube
1

1 = 1

Try again? (Y/N)

Y

Enter the cube
2

INVALID INPUT.

Enter the cube
3

INVALID INPUT.

Enter the cube
4

INVALID INPUT.

Enter the cube
5

INVALID INPUT.

Enter the cube
6

INVALID INPUT.

Enter the cube
7

INVALID INPUT.

Enter the cube
8

8 = 1
2

Try again? (Y/N)

N

как вы можете видеть, до тех пор, пока вы вводите "y" или "Y", он продолжает работать, когда вы вводите выходы программы, как вы хотели!

Кстати, ваш код не компилируется. Вот класс Java, который компилируется и запускается успешно. Причина, по которой ваш код не может быть скомпилирован, заключается в том, что

1) вы не указали основной метод класса правильно 2) вы не создали экземпляр класса, поэтому вы не могли вызвать метод так, как вы пытались (это привело к ошибкам компиляции).

См. Следующий код, который работает:

 import java.util.*;
         class CUBE {   

        public static void main(String[] args)   {              /*gives a series of consecutive odd numbers                                          
                                       whose sum is equal to the input value.  
                                       input is a cube of a number less than 1000*/

                int i,odd,t,sum,cube,n; 
                String c="y"; 
                System.out.println("c is : " + c);
                Scanner sc=new Scanner(System.in);        

                do
                {
                    i=1;
                    odd=1;
                    t=2;
                    sum=0;
                    System.out.println("\nEnter the cube");
                    cube=sc.nextInt(); //input is stored in 'cube'
                    CUBE myCube = new CUBE();
                    n=myCube.cubeRoot(cube);  /*'n' is the cube root of 'cube'. If 'cube'  
                                         is not a perfect cube then n=0*/


                  while(i<=n) 

                    {
                        sum+=odd;  //consecutive odd numbers are are added in sum    
                       if(sum==cube) //loop stops if sum=cube
                        {
                            break;
                        }
                        else if(i==n && sum!=cube)
                        {
                            i=1; //counter goes back to 1
                            sum=0;
                            odd=i+t; //odd becomes the next odd number just after 1 and then the one after that
                            t+=2;
                        }
                        else
                        {
                            i++; 
                            odd+=2;
                        }
                    }
                    if(n!=0) //if 'cube' is a perfect cube then n will never be 0
                    {
                       System.out.print("\n"+cube+" = ");
                       for(i=1;i<=n;i++,odd-=2) //i gives the required odd numbers of the series
                       {
                             System.out.println(i);
                       }
                       System.out.println("\nTry again? (Y/N)\n"); 
                       Scanner sc2=new Scanner(System.in);                                 
                       c=sc2.nextLine();
                    } 
                }
                while(c.equals("y")||c.equals("Y"));//if c is "y" then loop should run again but it doesnt
            }


            int cubeRoot(int cube)  {                    /*returns the cube root of 
                                                          cube and returns 0 if its 
                                                          invalid */

                int i;
                for(i=1;i<=1000;i++)//n sholud be less than 1000
                {
                    if(i*i*i==cube) //if i^3 = cube then n=i
                      return i;
                }
                System.out.println("\nINVALID INPUT.");//prints if cube is not a perfect cube 
                return 0;
            }} 
  • 0
    @ adrCoder - он успешно компилируется в BlueJ !! спасибо за эту вторую идею сканера :)
  • 0
    @AnantMishra рад, что это работает. Пожалуйста, примите мой ответ, как описано здесь: meta.stackexchange.com/questions/5234/…

Ещё вопросы

Сообщество Overcoder
Наверх
Меню