简体   繁体   English

Java赋值不知道是什么错误

[英]Java assignment don't know what is the mistake

the question is : 问题是 :

A fruit shop sells several types of fruits each day. 水果店每天出售几种水果。 Write a program that reads from user several lines of input.Each line includes a fruit's name,price per kilogram (as an integer), number of kilograms sold (as an integer). 编写一个程序,从用户读取几行输入。每行包括一个水果的名称,每千克的价格(作为整数),销售的公斤数(作为整数)。

the program should calculate and print the earned money of all fruits sold and fruit that achieved largest profit. 该计划应计算和打印所有销售的水果和获得最大利润的水果的收入。

hint: -you could assume that user will insert valid data -user could stop the program via entering the word "stop" as a fruit's name. 提示: - 您可以假设用户将插入有效数据 - 用户可以通过输入单词“stop”作为水果的名称来停止程序。

Sample input and out put: 样品输入和输出:

in each line, insert a fruit's name, price per kilogram, number of kilograms sold. 在每行中,插入水果的名称,每千克的价格,销售的公斤数。 To halt the program,insert "stop" as a fruit's name 要暂停程序,请插入“停止”作为水果的名称


banana 2 11 mango 3 8 peach 4 5 香蕉2 11芒果3 8桃4 5

stop


the earned money of all fruits sold: 66 fruit that achieved the largest profit: mango 所有水果销售的赚来的钱:获得最大利润的66种水果:芒果


what i wrote now: 我现在写的:

public static void main(String[] args) { 
// TODO code application logic here 
Scanner input = new Scanner (System.in); 
String fruitname= " "; 
String maxfruit = " "; 
int price = 0,number=0; 
int sum=0; 
int max=0; 


System.out.print("Fruit name, " + "price in killogram, number of killogram sold: "); 

while (!fruitname.equals("stop")) 
{ 
fruitname = input.next(); 
price = input.nextInt(); 
number = input.nextInt(); 
} 
if (fruitname.equals("stop")) 
{ 
sum = sum+(price*number); 

} 
if (max<(price*number)) 
{ 
max = price*number; 
maxfruit = fruitname; 
} 


System.out.println("the earned money of all fruits is " + sum); 
System.out.println("fruit that achieved the largest profit is "+ maxfruit); 
} 
} 

the program is not reading what i submit to it, don't know why and not giving me the sum and the max fruit.. what is the problem of what i wrote? 该程序没有阅读我提交给它的内容,不知道为什么而不给我总和和最大的成果..我写的是什么问题?

As you can see your reads happen in the while loop: 正如您所看到的,您的读取发生在while循环中:

while (!fruitname.equals("stop")) 
{ 
    fruitname = input.next(); 
    price = input.nextInt(); 
    number = input.nextInt(); 
} 

Every time it loops - it overrides the values. 每次循环 - 它都会覆盖值。 Finally when you read stop and exit the loop - your fruitname is stop . 最后,当你读取停止并退出循环时 - 你的fruitname就会停止 So you need to fix your logic on how you would want to read in the input 所以你需要修改你想要在输入中读取的逻辑

Working variant: 工作变体:

public class FruitTest {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);


    System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");

    String text = input.nextLine();

    String[] words = text.split(" ");

    List<Fruit> fruits = parseInput(words);

    int sum = getSum(fruits);

    String popular = getPopularFruitName(fruits);

    System.out.println("Got fruits: " + fruits.toString());
    System.out.println("the earned money of all fruits is " + sum);
    System.out.println("fruit that achieved the largest profit is " + popular);
}

private static String getPopularFruitName(List<Fruit> fruits) {
    int max = 0;
    String name = null;

    for (Fruit fruit : fruits) {
        int checkVal = fruit.getPrice() * fruit.getAmount();
        if(checkVal > max) {
            max  = checkVal;
            name = fruit.getName();
        }
    }

    return name;
}

private static int getSum(List<Fruit> fruits) {
    int result = 0;
    for (Fruit fruit : fruits) {
        result += fruit.getPrice() * fruit.getAmount();
    }
    return result;
}

private static List<Fruit> parseInput(String[] words) {
    List<Fruit> result = new ArrayList<Fruit>();
    int element = 1;
    final int name = 1;
    final int price = 2;
    final int amount = 3;

    Fruit fruit = null;
    for (String word : words) {
        if (word.equals("stop") || word.isEmpty()) {
            break;
        }
        if(element > amount)
            element = name;

        switch (element) {
            case name:
                fruit = new Fruit(word);
                result.add(fruit);
                break;
            case price:
                if (fruit != null) {
                    fruit.setPrice(Integer.valueOf(word));
                }
                break;
            case amount:
                if(fruit != null) {
                    fruit.setAmount(Integer.valueOf(word));
                }
                break;
        }
        element++;
    }

    return result;
}

static class Fruit {
    String name;
    int price  = 0;
    int amount = 0;


    Fruit(String name) {
        this.name = name;
    }

    String getName() {
        return name;
    }

    int getPrice() {
        return price;
    }

    void setPrice(int price) {
        this.price = price;
    }

    int getAmount() {
        return amount;
    }

    void setAmount(int amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return name + ". $" + price +
               ", amount=" + amount;
    }
}
}

Comments to code - it's proper way to parse all the inputted string and parse it to an object that stores all the data - name, price and amount. 对代码的注释 - 它是解析所有输入字符串并将其解析为存储所有数据的对象的正确方法 - 名称,价格和金额。 Store all parsed objects into array or a list and then calculate max and popular fruit while looping your parsed fruit array 将所有已解析的对象存储到数组或列表中,然后在循环解析的水果数组时计算最大和常用水果

I found some mistake. 我发现了一些错误。 The most important was in the while condition. 最重要的是在条件下。 Check this out. 看一下这个。

public static void main(String[] args) { 
    // TODO code application logic here 
    Scanner input = new Scanner (System.in); 
    String fruitname = null;
    String maxfruit = null;
    int fruitSum = 0;
    int totalSum = 0; 
    int max = 0; 

    System.out.print("Fruit name, " + "price in killogram, number of killogram sold: "); 


    while(!(fruitname = input.next()).equals("stop")){
        fruitSum = input.nextInt() * input.nextInt();
        totalSum += fruitSum;
        if(fruitSum > max){
            maxfruit = fruitname;
            max = fruitSum;
        }

    }

    System.out.println("the earned money of all fruits is " + totalSum); 
    System.out.println("fruit that achieved the largest profit is "+ maxfruit); 
} 
} 

Oh it is reading it. 哦,它正在读它。

the problem is that it doesn't do what you want it to do. 问题是它不能做你想做的事。

the problems with the code I can see are this: 我能看到的代码问题是这样的:

  • you are not storing the fruits quantities or prices anywhere, you need to store the values in an array or something (maxFruit,MaxValue) to compare them later. 您没有在任何地方存储水果数量或价格,您需要将值存储在数组或其他内容(maxFruit,MaxValue)以便稍后进行比较。
  • when you are reading the fruit values and a "stop" string is input the next step in your code is to wait for the price so it won't get out of the loop even if you input "stop", you need to restructure your scanner loop. 当您正在读取水果值并输入“停止”字符串时,代码中的下一步是等待价格,即使您输入“停止”也不会退出循环,您需要重新构建扫描仪循环。

And if it is a beginner class it may be ok, but the code you are writing is not object oriented don't write the logic in the main. 如果它是一个初学者类,它可能没问题,但是你编写的代码不是面向对象的,不会在main中编写逻辑。

You may want to learn to debug it is a very useful tool when you are learning to code, if you run this program in debug mode , you could see that the values are getting input and everything that is happening, Netbeans and Eclipse have very good debuggers and it would be worth to expend half an hour learning the basics of debugging It certainly helped me a lot when I was starting. 您可能想要学习调试它是一个非常有用的工具,当您学习编码时,如果您在调试模式下运行该程序,您可以看到值正在获取输入和发生的一切,Netbeans和Eclipse非常好调试器,花半小时学习调试的基础是值得的。当我开始时,它确实帮了我很多忙。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FruitSells {
    public static void main(String... args) {
        BufferedReader bufer = new BufferedReader(new InputStreamReader(System.in));
        try {
            String str;
            String[] inarr;
            int sumMoney = 0;
            do {
                str = (String) bufer.readLine();
                inarr = str.split(" ");
                for(int i = 1; i < inarr.length; i += 3) {
                    sumMoney += Integer.parseInt(inarr[i]) * Integer.parseInt(inarr[i + 1]);
                }
                System.out.println(sumMoney);
                sumMoney = 0;
            } while (!str.equals("stop"));


        } catch(IOException ex) {
            System.out.println("Problems with bufer.readLine()");
        }
    }
}

something like this you can modernize it.sorry for eng i can not speak))and write correctly of course)) 像这样的东西,你可以现代化it.sorry for eng我不会说话))并且当然写得正确))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM