gpt4 book ai didi

java - 循环未按预期工作

转载 作者:行者123 更新时间:2023-12-01 22:00:18 24 4
gpt4 key购买 nike

我必须创建一个为包创建标签的 java 代码。当用户输入“y”或“Y”来响应“您想创建更多”时,它将再次进行循环。如果用户输入“y”或“Y”以外的任何内容,它将退出循环。我遇到的问题是,在用户输入所有信息并被问到问题后,如果用户说出 y 或 Y 以外的任何内容,它会退出程序,但不会输出任何标签信息。如果我输入 y 或 Y,它会正确输出标签信息并再次完美地运行循环。只是想知道是否有人可以帮助我看看我做错了什么,以便我可以在输入 y 或 Y 以外的任何内容后让它输出标签信息。

import javax.swing.JOptionPane;

public class MailOrderAFG //Define my public class
{
public static void main(String [] args)
{
String title, firstName, lastName, streetAddress, city, state, zip, numBoxesInput, enterAnother;
String a = "y", b = "Y";
title = JOptionPane.showInputDialog("Enter title (Mr., Mrs., Ms., etc.): ");
firstName = JOptionPane.showInputDialog("Enter first name: ");
lastName = JOptionPane.showInputDialog("Enter last name: ");
streetAddress = JOptionPane.showInputDialog("Enter street address: ");
city = JOptionPane.showInputDialog("Enter city: ");
state = JOptionPane.showInputDialog("Enter state: ");
zip = JOptionPane.showInputDialog("Enter zip code: ");
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order: ");
enterAnother = JOptionPane.showInputDialog ("Do you want to produce more labels? Y or N ");
int numBoxes = 0;
int i;


while(enterAnother.equals(a) || enterAnother.equals(b)) //priming read

{



numBoxes = Integer.parseInt(numBoxesInput); //changing string to int so we can do arithmatic with it
{


for (i = 1; i <= numBoxes; i++) { //adding one until i is equal to numBoxes, then it will exit the loop
System.out.println(title + " " + firstName + " " + lastName);
System.out.println(streetAddress);
System.out.println(city + ", " + state + " " + zip);
System.out.println("Box " + i + " of " + numBoxes);
System.out.println();}



title = JOptionPane.showInputDialog("Enter title (Mr., Mrs., Ms., etc.): ");
firstName = JOptionPane.showInputDialog("Enter first name: ");
lastName = JOptionPane.showInputDialog("Enter last name: ");
streetAddress = JOptionPane.showInputDialog("Enter street address: ");
city = JOptionPane.showInputDialog("Enter city: ");
state = JOptionPane.showInputDialog("Enter state: ");
zip = JOptionPane.showInputDialog("Enter zip code: ");
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order: ");
enterAnother = JOptionPane.showInputDialog ("Do you want to produce more labels? Y or N ");

}

}

System.exit(0);

}
}

最佳答案

我可以看到您通过尝试复制并粘贴原始代码来创建循环,但生成的代码的工作流程不正确。

看,您的代码目前是这样的:

FETCH INFO FROM USER
ASK IF USER WANTS MORE

while (WANTSMORE)
PRINT INFO

FETCH INFO FROM USER
ASK IF USER WANTS MORE
end while

end program

看,实际上应该是这样的:

do
FETCH INFO FROM USER
ASK IF USER WANTS MORE
PRINT INFO
while (WANTSMORE)

end program

看看是否可以重新排序代码以便更正工作流程。检查this link如果您需要有关do-while的信息。

关于java - 循环未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33640946/

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