Метод, возвращающий нуль, независимо от того, что - PullRequest
0 голосов
/ 17 октября 2018

У меня есть два класса, которые я разместил здесь (плюс компьютерный класс, из которого создаются объекты).

Когда я пытаюсь использовать свой метод findSys, мой метод возвращает значение «ноль», несмотря ни на что.Я пытаюсь сравнить переменную "search", которую пользователь вводит как параметр findSys, с нулем, и если он равен null, он должен вывести сообщение, которое у меня есть под предложением "else".Но вместо этого он просто возвращает ноль, несмотря ни на что.Застрял здесь.

import java.util.Scanner;

public class SystemTester {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        String search;
        ComputerStore cpu1 = new ComputerStore();

        cpu1.add("Pentium II", 32, "2080", "Asus 370", "Corsair", 5, 123, 5);
        cpu1.add("Pentium I", 16, "Nvidia 1080", "Asus 270", "CoolerMaster1", 5, 123, 5);
        cpu1.add("Pentium III", 4, "GTX 1060", "Gigabyte", "Corssair 2", 5, 123, 5);
        cpu1.add("AMD", 4, "GTX 980", "Gigabyte", "Corssair 2", 5, 123, 5);
        cpu1.add("AMD Ryzen", 4, "GTX 680", "Gigabyte", "Corssair 2", 5, 123, 5);
        cpu1.add("Core I5", 4, "GTX 1080ti", "Gigabyte", "Corssair 2", 5, 123, 5);
        cpu1.add("Core I7", 4, "GTX 1060 SLI", "Gigabyte", "Corssair 2", 5, 123, 5);
        cpu1.add("Core I9", 4, "GTX 780", "Gigabyte", "Corssair 2", 5, 123, 5);
        cpu1.add("AMD Ryzen 2", 4, "Voodoo2", "Gigabyte", "Corssair 2", 5, 123, 5);
        cpu1.add("I7 5820k", 4, "Voodoo1", "Gigabyte", "Corssair 2", 5, 123, 5);

        ComputerStore cpu2 = new ComputerStore();
        cpu2.add("Haswell", 64, "Nvidia 1080", "Aztek", "Corsair", 3.5, 455, 5.5);



        System.out.println("Please enter a CPU to search for (Press q to quit)");
        search = scan.nextLine();
        while (!"q".equals(search)) {

            if (search != null) {
                System.out.println(cpu1.findSys(search));
            } 
            else {
                if (search.equals(null))
                    System.out.println("test");
            }

            System.out.println("Please enter a CPU to search for (Press q to quit)");
            search = scan.nextLine();
        }

    }
}


public class ComputerStore {
    private Computer[] systems;
    private int sysNumbers;

    public ComputerStore() {
        systems = new Computer[200];
        sysNumbers = 0;
    }

    public void add(String c, int r, String g, String m, String p, double co, int sn, double d) {
        systems[sysNumbers++] = new Computer(c, r, g, m, p, co, sn, d);

    }

    public String toString() {
        String result = "";
        for (int i = 0; i < sysNumbers; i++)
            result += systems[i].toString() + "\n";
        return result;

    }

    public String findSys(String c) {
        for (int i = 0; i < sysNumbers; i++) {
            if (systems[i] != null && systems[i].getCpu().equals(c))
                return systems[i].getMotherboard();

        }
        return null;
    }
}

//
//This program will create Computer objects with different data members
//and will also upgrade those data members based on setters.  This program
//also has a depreciation function and upgrade function.  This (Computer) is the class
//and the SystemBuilder class is the class used for creating the objects.
public class Computer {
    // Data Members - These belong to the class and are private.
    // They all go to new objects.
    private String cpu;
    private int ram;
    private String gpu;
    private String motherboard;
    private String psu;
    private double cost;
    private int serialnumber;
    private double depreciation;

    // Initial constructor with no arguments
    Computer() {
        cpu = "";
        ram = 0;
        gpu = "";
        motherboard = "";
        psu = "";
        cost = 0.0;
        serialnumber = 0;
        depreciation = 0.0;
    }

    // Constructor with data members
    Computer(String c, int r, String g, String m, String p, double co, int sn, double d) {
        cpu = new String(c);
        ram = r;
        gpu = new String(g);
        motherboard = new String(m);
        psu = new String(p);
        cost = co;
        serialnumber = sn;
        depreciation = d;

    }

    // Getters, allow retrieval of data members from outside of class
    public String getCpu() {
        return cpu;
    }

    public int getRam() {
        return ram;
    }

    public String getGpu() {
        return gpu;
    }

    public String getMotherboard() {
        return motherboard;
    }

    public String getPsu() {
        return psu;
    }

    public double getCost() {
        return cost;
    }

    public int getSerialnumber() {
        return serialnumber;
    }

    public double getDepreciation() {
        return depreciation;
    }
    // Setters, allow setting of data members from outside of class

    public void setCpu(String c) {
        cpu = new String(c);
    }

    public void setRam(int r) {
        ram = r;
    }

    public void setGpu(String g) {
        gpu = new String(g);
    }

    public void setMotherboard(String m) {
        motherboard = new String(m);
    }

    public void setPsu(String p) {
        psu = new String(p);
    }

    public void setCost(double co) {
        cost = co;
    }

    public void setSerialnumber(int sn) {
        serialnumber = sn;
    }

    public void setDepreciation(double d) {
        depreciation = d;
    }

    // Boolean below will compare computers to see if equal
    // based on same motherboard SN#.
    public boolean equals(Computer c) {
        if (this.serialnumber == (c.serialnumber)) {
            return true;
        } else {
            return false;
        }
    }

    // To string method will print characteristics about object.


    public String toString() {
        return ("CPU:\t\t" + cpu + "\n" + "RAM:\t\t" + ram + "\n" + "GPU:\t\t" + gpu + "\n" + "Motherboard:\t"
                + motherboard + "\n" + "PSU:\t\t" + psu + "\n" + "Cost:\t\t" + "$" + cost + "\n" + "SN#:\t\t"
                + serialnumber + "\n" + "Depreciation:\t" + "$" + depreciation + " (annually)");
    }
    // A method to depreciate the cost of the computer
    // The formula is observed below, but this is a
    // straight line depreciation equation, calculated based
    // on the values the user passes into the function. This method
    // will show an output of annual depreciation based on useful
    // life, entered in "years" by the user.
    public void depreciate(double purchasePrice, double salvageValue, double lifeSpanYears) {
        double depreciableCost;
        double annualDepreciation;
        depreciableCost = purchasePrice - salvageValue;
        annualDepreciation = depreciableCost / lifeSpanYears;
        depreciation = annualDepreciation;
    }

    // A method to upgrade the ram or the video card
    // The method will accpet argumetns for ram (in int) and a gpu (string).
    public void upgrade(int newRam, String newGpu) {
        ram = newRam;
        gpu = new String(newGpu);
    }

}

Ответы [ 3 ]

0 голосов
/ 17 октября 2018

Вы не хотите сравнивать, если search == null, потому что search - пользовательский ввод.Вы хотите проверить, является ли результат поиска null:

while (!"q".equals(search)) {
    Computer searchResult = cpu1.findSys(search);
    if (searchResult != null) {
        System.out.println(searchResult);
    } 
    else {
        System.out.println("not found");
    }

Вам также следует изменить тип возвращаемого значения findSys на Computer.Возврат только String ограничивает полезность функции:

public Computer findSys(String c) {
    for (int i = 0; i < sysNumbers; i++) {
        if (systems[i] != null && systems[i].getCpu().equals(c))
            return systems[i];
    }
    return null;
}
0 голосов
/ 17 октября 2018

Хорошо,

Мистер.Мопп был прав - но мне пришлось удалить класс Computer перед переменной searchResult, чтобы он работал, и создать переменную типа String, SearchResult.Так что это работает для меня ниже:

String searchResult;
while (!"q".equals(search)) {
    searchResult = cpu1.findSys(search);
    if (searchResult != null) {
        System.out.println(searchResult);
    } 
    else {
        System.out.println("not found");
    }
0 голосов
/ 17 октября 2018

Для меня ваша реализация отлично работает.Здесь я прикрепил скриншот, может быть, вы что-то сделали не так во время ввода с консоли, когда вы принимаете текст для поиска ввода. Вывод консоли снимок

...