2015-07-03 5 views
0

У меня есть этот код прямо сейчас, который печатает, является ли целое положительным/отрицательным, нечетным/четным, простым/составным. Я просто хочу, чтобы значение kctr было напечатано в функцию печати после того, как я вызвал метод kCheck. Цикл является правильным, но после вызова kCheck он просто печатает 0.Печать значения из другого метода в том же классе

import javax.swing.JOptionPane; 

public class FirstClass 
{ 

    public int kCheck(int num, int k, int kctr) 
    { 
     for(int l=1;l<num+1;l++){ 
      if((num%l) == 0){ 
       kctr++; 
       //System.out.println("" +kctr); Just to check if the loop is corrrect 
      } 
     } 
     return kctr; 
    } 

    public static void main (String args[]) 
    { 
     CheckClass checker = new CheckClass(); 
     FirstClass checker2 = new FirstClass(); 
     int num = 0; 
     int even = 0; 
     int odd = 0; 
     int negeven = 0; 
     int negodd = 0; 
     int k = 0; 
     int kctr = 0; 
     num = Integer.parseInt(JOptionPane.showInputDialog (null, "Input an integer.", JOptionPane.QUESTION_MESSAGE)); 

     boolean ch=true; 

     while(ch){ 
      if(num%2 == 0 && num>0){ 
       ch=false; 
       even = 1; 
      } 
      else if(num%2 == 1 && num>0){ 
       checker2.kCheck(num, k, kctr); 
       odd = 1; 
       System.out.println("" +kctr); /*Just to check if the loop is correct and the problem is here. 
               It prints the value of kctr on the method kCheck but when it comes to here, it prints 0.*/ 
      } 
      else if(num%2 == 0 && num < 0){ 
       negeven = 1; 
      } 
      else if(num%2 == 1 && num < 0){ 
       negodd = 1; 
      } 
      break; 
     } 

     if(even == 1){ 
      checker.posEvenCheck(num); 
     } 
     if(odd == 1){ 
      checker.posOddCheck(num, kctr); 
     } 
     if(negeven == 1){ 
      checker.negEvenCheck(num); 
     } 
     if(negodd == 1){ 
      checker.negOddCheck(num); 
     } 
    } 
} 
+0

Вы не заявили проблему вы сейчас работаете. Я подозреваю, что просто вы пытаетесь вызвать метод экземпляра без указания экземпляра - если вы выполните поиск сообщения об ошибке, вы получите много похожих вопросов ... –

ответ

3

Изменить эту часть кода:

else if(num%2 == 1 && num>0){ 
    checker2.kCheck(num, k, kctr); 
    odd = 1; 
    System.out.println("" +kctr); /*Just to check if the loop is correct and the problem is here. 
            It prints the value of kctr on the method kCheck but when it comes to here, it prints 0.*/ 
} 

To:

else if(num%2 == 1 && num>0){ 
    kctr = checker2.kCheck(num, k, kctr); // <- Assign the return value of the method to kctr 
    odd = 1; 
    System.out.println("" +kctr); 
} 
+0

Спасибо! Ты спасатель жизни. Я сделал все, но не получил ответа. Благодаря! –

Смежные вопросы