gpt4 book ai didi

java - Netbeans 的 Java 代码中的 while 循环

转载 作者:行者123 更新时间:2023-12-01 12:25:15 25 4
gpt4 key购买 nike

import java.util.ArrayList;
import javax.swing.JOptionPane;

public class MainApp {

public static void main(String[] args) {

ArrayList<Product> cart = new ArrayList<Product>();

String s1 = JOptionPane
.showInputDialog("Please enter the quantity of the product you have selected");

int r = Integer.parseInt(s1);

String s2 = JOptionPane
.showInputDialog("Please enter the name of the product");

String s3 = JOptionPane
.showInputDialog("Please enter the price of the product");
double d1 = Double.parseDouble(s3);

for (int i = 0; i < r; i++) {

Product p1 = new Product();
p1.setName(s2);
p1.setPrice(d1);

cart.add(p1);

}

double total_price = 0;
for (int i = 0; i < cart.size(); i++) {
total_price = total_price + cart.get(i).getPrice();
}

JOptionPane.showMessageDialog(null, cart.toString()
+ "The total price of all the products in the cart is : "
+ total_price + " KD", "Shopping Information",
JOptionPane.INFORMATION_MESSAGE);

cart.removeAll(cart);

JOptionPane.showMessageDialog(null, "Thank you for shopping with us! ",
"Prompt", JOptionPane.INFORMATION_MESSAGE);

String s4 = JOptionPane
.showInputDialog("Would you like to add items to your cart");

while (s4 != "stop") {

String s5 = JOptionPane
.showInputDialog("Please enter the name of the product");

String s6 = JOptionPane
.showInputDialog("Please enter the price of the product");
double d2 = Double.parseDouble(s6);

Product p2 = new Product();

p2.setName(s5);
p2.setPrice(d2);

cart.add(p2);

String s7 = JOptionPane
.showInputDialog("Would you like to add more items?");
if (s7 == "No" || s7 == "no")
s4 = "stop";

}

JOptionPane.showMessageDialog(null, cart.toString(), "Cart Details",
JOptionPane.INFORMATION_MESSAGE);

}

}

一切工作正常,直到 while 循环......不知怎的,我无法让它为我工作。当我在末尾输入“否”或“否”时,循环将继续运行,直到我为字符串问题输入空格为止。它只是在最后给了我以下错误:

Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1008)
at java.lang.Double.parseDouble(Double.java:540)
at mainapp.MainApp.main(MainApp.java:66)
Java Result: 1
BUILD SUCCESSFUL (total time: 41 seconds)

最佳答案

尝试:

while(!s4.equals("stop")){ 

String 是一个对象,而不是原始类型,因此您必须使用 .equals 而不是 ==。

关于java - Netbeans 的 Java 代码中的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26405333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com