Использование переменных образуют другие классы в Java - PullRequest
0 голосов
/ 18 октября 2019

Я пытаюсь использовать две переменные типа int из других классов другого класса, а затем добавить их вместе в другую переменную и распечатать результат. Когда я пытаюсь это сделать, я всегда получаю нулевой результат, как будто значения не переносятся в новый класс, и я не могу понять, в чем проблема. Вот пример кода:

class1

public static int finished = (match2.totalpoints + match3.iq);
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
        System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
        System.out.println("");
        System.out.println("When taking the quiztest you have only two seconds before making each guess");
        match2 m = new match2();
        System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
        }
}

EDIT: class2

 public class match2 {

    public static int totalpoints;
    int a;
    int b;
    int c;
    int d;
    int e;
    int f;
    String guess;
    String group;

    String countdown[] = {
    "3...",
    "2...",
    "1...",
    ""
    };

    String memorize[] = {
    ""
    };
public match2() throws InterruptedException
    {
        int x = set2();
        int y = set3();
        int z = set4();
        total(x, y, z);
        System.out.println("For the next part of your IQ ASSesment\njust type back the words in CAPSLOCK in CAPSLOCK");
        System.out.println("");
        match3 n = new match3();            
    }

public void set1() throws InterruptedException 
    {
        //Scanner s = new Scanner(System.in);
        for (int i = 0; i < countdown.length; i++) 
            {
                Thread.sleep(750);
                System.out.println(countdown[i]); 
            }
    }

public int set2() throws InterruptedException
    {
        Random r = new Random();
        Scanner s = new Scanner(System.in);
        System.out.println("press ENTER for your first set...");
        s.nextLine();
        set1(); 

        int rv = 0;
        a = r.nextInt(9) + 1;
        b = r.nextInt(9) + 1;
        c = r.nextInt(9) + 1;
        d = r.nextInt(9) + 1;
        group = "" + a  + b + c + d;
        System.out.println(group);
        for (int i = 0; i < memorize.length; i++) 
        {
            Thread.sleep(1500);
            System.out.println(memorize[i]); 
        }
        System.out.println("\n\n\n\n\n\n\n\n\n\n");
        guess = "" + s.nextLine();
        if(guess.equals(group))
        {
            System.out.println("nice +1 bruh");
            rv = 1;
        }
        else if(!guess.equals(group))
        {
            System.out.println("almost");
        }
        return rv;
    }


public int set3() throws InterruptedException
    {
        Random r = new Random();
        Scanner s = new Scanner(System.in);
        System.out.println("");
        System.out.println("press ENTER for your next set...");
        s.nextLine();
        set1(); 

        int rv = 0;
        a = r.nextInt(9) + 1;
        b = r.nextInt(9) + 1;
        c = r.nextInt(9) + 1;
        d = r.nextInt(9) + 1;
        f = r.nextInt(9) + 1;
        group = "" + a  + b + c + d + f;  
        System.out.println(group);
        for (int i = 0; i < memorize.length; i++) 
        {
            Thread.sleep(1500);
            System.out.println(memorize[i]); 
        }
        System.out.println("\n\n\n\n\n\n\n\n\n\n");
        guess = s.nextLine();      
        if(group.equals(guess))     
        {
            rv = 1;
            System.out.println("good");
        }
        else if(!guess.equals(group))
        {
            System.out.println("almost");
        }
        return rv;
    }

public int set4() throws InterruptedException
{
    Random r = new Random();
    Scanner s = new Scanner(System.in);
    System.out.println("");
    System.out.println("press ENTER for your final set...");
    s.nextLine();
    set1(); 

    int rv = 0;
    a = r.nextInt(9) + 1;
    b = r.nextInt(9) + 1;
    c = r.nextInt(9) + 1;
    d = r.nextInt(9) + 1;
    e = r.nextInt(9) + 1;
    f = r.nextInt(9) + 1;
    group = "" + a  + b + c + d + f + e;
    System.out.println(group);
    System.out.println("");
    for (int i = 0; i < memorize.length; i++) 
    {
        Thread.sleep(1500);
        System.out.println(memorize[i]); 
    }
    System.out.println("\n\n\n\n\n\n\n\n\n\n");
    guess = "" + s.nextLine();
    if(group.equals(guess))
        {
            rv = 1;
            System.out.println("great");
        }
    else if(!group.equals(guess))
        {
        System.out.println("eeeh buzer sound");
        }
    return rv;
}

public int total(int x, int y, int z)
    {
    System.out.println("");
    int totalpoints = (x + y + z);
    if(totalpoints == 3)
    {
        System.out.println("YOU GOT THEM ALL");
    }
    if(totalpoints <= 2 && totalpoints >= 1)
    {
        System.out.println("YOU MISSED A TOTAL OF  " + (3 - totalpoints));
    }
    if(totalpoints == 0)
    {
        System.out.println("HA! YOU MISSED THEM ALL");
    }
    return totalpoints;
}

}

EDIT: class3

public class match3 {
    public static int iq;

    String countupdown [] = {
            "READY...", 
            "SET.....",
            ""
            };
    String memorize [] = {
            ""
            };

public match3() throws InterruptedException
    {
        int mem1 = memory1();
        int mem2 = memory2();
        int mem3 = memory3();
        totalMemory(mem1, mem2, mem3);
    }

public void methodCountdown() throws InterruptedException
    {
    for(int i = 0; i < countupdown.length; i++)
        {
            Thread.sleep(1000);
            System.out.println(countupdown[i]);
        }

    }

public int memory1() throws InterruptedException
    {
        int rv = 1;
        Scanner s = new Scanner(System.in);
        System.out.println("Press ENTER when ready");
        s.nextLine();
        methodCountdown();
        String a = word1();
        String b = word2();
        System.out.println("The " + a + " ate the " + b);
        String wordgroup = "" + a + " " + b;
        for (int i = 0; i < memorize.length; i++) 
        {
            Thread.sleep(1500);
            System.out.println(memorize[i]); 
        }
        System.out.println("\n\n\n\n\n\n\n\n\n\n");
        String wordguess = "" + s.nextLine(); 
        if(wordgroup.equals(wordguess))
            {
                System.out.println("awesome cock muncher a match");
                rv = 1;
            }
        else if(!wordgroup.equals(wordguess))
            {
            System.out.println("nope");
            }
        return rv;
    }

public int memory2() throws InterruptedException
    {
        int rv = 0;
        Scanner s = new Scanner(System.in);
        System.out.println("");
        System.out.println("Press ENTER for your next set");
        s.nextLine();
        methodCountdown();
        String a = word1();
        String c = word3();
        System.out.println("The " + a + " drove the " + c);
        String wordgroup = "" + a + " " + c;
        for (int i = 0; i < memorize.length; i++) 
        {
            Thread.sleep(1500);
            System.out.println(memorize[i]); 
        }
        System.out.println("\n\n\n\n\n\n\n\n\n\n");
        String wordguess = "" + s.nextLine(); 
        if(wordgroup.equals(wordguess))
            {
                System.out.println("awesome cock muncher a match");
                rv = 1;
            }
        else if(!wordgroup.equals(wordguess))
            {
            System.out.println("nope");
            }
        return rv;
    }

public int memory3() throws InterruptedException
    {
        int rv = 0;
        Scanner s = new Scanner(System.in);
        System.out.println("");
        System.out.println("Press ENTER for your next set");
        s.nextLine();
        methodCountdown();
        String a = word1();
        String d = word4();
        System.out.println("The " + a + " visited the " + d);
        String wordgroup = "" + a + " " + d;
        for (int i = 0; i < memorize.length; i++) 
        {
            Thread.sleep(1500);
            System.out.println(memorize[i]); 
        }
        System.out.println("\n\n\n\n\n\n\n\n\n\n");
        String wordguess = "" + s.nextLine(); 
        if(wordgroup.equals(wordguess))
            {
                System.out.println("awesome cock muncher a match");
                rv = 1;
            }
        else if(!wordgroup.equals(wordguess))
            {
            System.out.println("nope");
            }
        return rv;
    }

public static String word1()
    {
        String word = "";
        Random r = new Random();
        int cv = r.nextInt(3) + 1;
        if(cv == 1)
        {
            word = "DOG";
        }
        else if(cv == 2)
        {
            word = "CAT";
        }
        else if(cv == 3)
        {
            word = "BIRD";
        }
    return word;
}

    public static String word2()
        {
            String word = "";
            Random r = new Random();
            int cv = r.nextInt(3) + 1;
            if(cv == 1)
            {
                word = "FOOD";
            }
            else if(cv == 2)
            {
                word = "MUD";
            }
            else if(cv == 3)
            {
                word = "GRAINS";
            }
            return word;
        }

    public static String word3()
        {
            String word = "";
            Random r = new Random();
            int cv = r.nextInt(3) + 1;
            if(cv == 1)
            {
                word = "TRAM";
            }
            else if(cv == 2)
            {
                word = "BUS";
            }
            else if(cv == 3)
            {
                word = "BICYCLE";
            }
        return word;
        }

    public static String word4()
        {
            String word = "";
            Random r = new Random();
            int cv = r.nextInt(3) + 1;
            if(cv == 1)
            {
                word = "MALL";
            }
            else if(cv == 2)
            {
                word = "PARK";
            }
            else if(cv == 3)
            {
                word = "POOL";
            }
        return word;
    }

public void totalMemory(int mem1, int mem2, int mem3)
    {   
        int iq = (mem1 + mem2 + mem3);
        System.out.println("");
        if(iq == 3)
            {
            System.out.println("YOU GOT THEM ALL");
            }
        else if(iq <= 2 || iq >= 1)
            {
            System.out.println("YOU MISSED  A TOTAL OF " + (3 - iq));
            }
        else if(iq == 0)
            {
            System.out.println("HA! YOU MISSED THEM ALL");
            }
    }

}

Общее количество очков - это переменная из класса match2 и iq из класса match3. Любая помощь с любыми методами, которые я мог бы использовать, чтобы это произошло, была бы очень признательна. Спасибо

Ответы [ 4 ]

1 голос
/ 18 октября 2019

Ну ... кроме того факта, что вы не следуете никаким соглашениям о коде, подобно тому, как имена классов должны начинаться с заглавной буквы, а открытые статические конечные поля (например, totalpoints и iq) должны быть все в верхнем регистре ( соглашения по коду * 1002)*, вы не используете match2 и match3 коды, без этого мы не сможем понять, что происходит внутри этих классов.

Но вы можете сделать простой тести присвойте значение match2.totalpoints и match3.iq , и вы увидите, как сумма этих двух значений будет напечатана последним указанным system.out.

удачи и хорошего изучения Java!

0 голосов
/ 18 октября 2019

Smth. нравится. У вас есть много дублирования кода

public class MatchRunner {

    public static void main(String... args) throws InterruptedException {
        new MatchRunner().start();
    }

    public void start() throws InterruptedException {
        System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
        System.out.println();
        System.out.println("When taking the quiztest you have only two seconds before making each guess");

        int totalPoints = new Match2().getTotalPoints();

        System.out.println("For the next part of your IQ Assesment");
        System.out.println("just type back the words in CAPSLOCK in CAPSLOCK");

        int iq = new Match3().getIQ();

        System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + (totalPoints + iq) + " POINTS");
    }
}

public class Match2 {

    public int getTotalPoints() throws InterruptedException {
        try (Scanner scan = new Scanner(System.in)) {
            int totalPoints = calc(scan, "first", "nice +1 try", "almost");
            totalPoints += calc(scan, "next", "good", "almost");
            totalPoints += calc(scan, "final", "great", "eeeh buzer sound");
            printTotalPoints(totalPoints);
            return totalPoints;
        }
    }

    private static void countdown() throws InterruptedException {
        for (int i = 5; i > 0; i--) {
            Thread.sleep(750);
            System.out.println(i + "...");
        }
    }

    private static int calc(Scanner scan, String strSet, String strEqual, String strNotEqual) throws InterruptedException {
        System.out.println("press ENTER for your " + strSet + " set...");

        Random random = new Random();
        scan.nextLine();
        countdown();

        int sum = 0;

        for (int i = 0; i < 4; i++)
            sum += random.nextInt(9) + 1;

        System.out.println(sum);

        for (int i = 0; i < 10; i++)
            System.out.println();

        int guess = scan.nextInt();
        System.out.println(guess == sum ? strEqual : strNotEqual);

        return guess == sum ? 1 : 0;
    }

    private static void printTotalPoints(int totalPoints) {
        System.out.println();

        if (totalPoints == 3)
            System.out.println("YOU GOT THEM ALL");
        else if (totalPoints <= 2 && totalPoints >= 1)
            System.out.println("YOU MISSED A TOTAL OF  " + (3 - totalPoints));
        else if (totalPoints == 0)
            System.out.println("HA! YOU MISSED THEM ALL");
    }

}

public class Match3 {

    public int getIQ() throws InterruptedException {
        try (Scanner scan = new Scanner(System.in)) {
            Random random = new Random();
            Supplier<String> getWord1 = () -> getWord(random, "DOG", "CAT", "BIRD");
            Supplier<String> getWord2 = () -> getWord(random, "FOOD", "MUD", "GRAINS");
            Supplier<String> getWord3 = () -> getWord(random, "TRAM", "BUS", "BICYCLE");
            Supplier<String> getWord4 = () -> getWord(random, "MALL", "PARK", "POOL");

            int iq = calc(scan, getWord1, getWord2, "ate the");
            iq += calc(scan, getWord1, getWord3, "drove the");
            iq += calc(scan, getWord1, getWord4, "visited the");
            printIq(iq);
            return iq;
        }
    }

    private static void countdown() throws InterruptedException {
        System.out.println("READY...");
        Thread.sleep(1000);
        System.out.println("SET...");
        Thread.sleep(1000);
    }

    public int calc(Scanner scan, Supplier<String> wordOne, Supplier<String> wordTwo, String strMsq) throws InterruptedException {
        System.out.println("Press ENTER when ready");
        scan.nextLine();

        countdown();

        String a = wordOne.get();
        String b = wordTwo.get();

        System.out.println("The " + a + ' ' + strMsq + ' ' + b);

        String wordGroup = a + ' ' + b;

        for (int i = 0; i <= 10; i++)
            System.out.println();

        String wordGuess = scan.nextLine();
        System.out.println(wordGroup.equals(wordGuess) ? "awesome cock muncher a match" : "nope");

        return wordGroup.equals(wordGuess) ? 1 : 0;
    }

    private static String getWord(Random random, String one, String two, String three) {
        int cv = random.nextInt(3) + 1;

        if (cv == 1)
            return one;
        if (cv == 2)
            return two;
        if (cv == 3)
            return three;
        return "";
    }

    public void printIq(int iq) {
        System.out.println();

        if (iq == 3)
            System.out.println("YOU GOT THEM ALL");
        else if (iq <= 2 || iq >= 1)
            System.out.println("YOU MISSED  A TOTAL OF " + (3 - iq));
        else if (iq == 0)
            System.out.println("HA! YOU MISSED THEM ALL");
    }
}
0 голосов
/ 18 октября 2019

Так что я наконец-то получил его на работу. Проблема, я думаю, заключалась в том, что я пытался сложить вместе переменные из других классов (match2 и match3) вне главной функции в классе (match1), который я пытался добавить вместе. Все, что я сделал, это переместил выражение, добавив переменные вместе сверху вниз в основную функцию следующим образом:

public static int finished;
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
        System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
        System.out.println("");
        System.out.println("When taking the quiztest you have only two seconds before making each guess");
        match2 m = new match2();

        finished = (match2.totalpoints + match3.iq);
        System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
        }

}

Спасибо всем за помощь.

0 голосов
/ 18 октября 2019

Переменные int, которые вы пытаетесь использовать внутри дочерних классов вашего основного родительского класса? Вы расширили дочерние классы в своем главном родительском классе?

Класс № 1:

public int firstVar(int someNum) {
  //code here
  return someNum;
}

Класс № 2:

public int secondVar(int otherNum) {
  //code here
  return otherNum;
}

Класс № 3 Класс с MainМетод -

public class mainClass extends class#1; //etc
//code here and finally print out the finished number

Вы можете попробовать расширить один из классов с нужным вам int на другой класс с другим необходимым вам int, а затем просто расширить этот второй класс на свой основной, ИЛИ вымог бы попытаться полностью переопределить ваши классы и просто поместить все нужные вам целые в один отдельный класс, а затем расширить этот единственный в свой основной.

...