gpt4 book ai didi

java - 为什么我的代码会跳过 if 语句?

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

我正在发布一段较大的代码块,但我遇到了问题。它应该自行运行。为了进行测试,只需在第一个提示时输入一个即可。一旦运行 print 语句,程序就会终止,而不是询问变量。我不明白为什么。有人可以帮助我吗?

import java.util.Scanner;

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

int switchNumber;
String variableCaseOne;
double distance;
double initialVelocity;
double time;
double gravity;

System.out.println("This section is for projectile motion.");
System.out.println("Which equation would you like to use?");
System.out.println("1. Horizontal Equation: D = Vi * t");
System.out.println("2. Vertical Equation: D = Vi * t - (1/2)g * (t^2)");
switchNumber = input.nextInt();
if (switchNumber == 1) {
System.out.println("Tell me which variable you'd like to solve for.");
variableCaseOne = input.nextLine();
if (variableCaseOne.equals("d")) {
System.out.println("Enter the Initial velocity.");
initialVelocity = input.nextDouble();
System.out.println("Enter the time.");
time = input.nextDouble();
System.out.println("Distance equals: " + initialVelocity * time);
}

}
}
}

谢谢大家的帮助!

最佳答案

如果我理解正确,请尝试改变

variableCaseOne = input.nextLine();

variableCaseOne = input.next();

这对我有用

snpt

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

int switchNumber;
String variableCaseOne;
double initialVelocity;
double time;

System.out.println("This section is for projectile motion.");
System.out.println("Which equation would you like to use?");
System.out.println("1. Horizontal Equation: D = Vi * t");
System.out.println("2. Vertical Equation: D = Vi * t - (1/2)g * (t^2)");
switchNumber = input.nextInt();
if (switchNumber == 1)
{
System.out.println("Tell me which variable you'd like to solve for.");
variableCaseOne = input.next();
if (variableCaseOne.equals("d"))
{
System.out.println("Enter the Initial velocity.");
initialVelocity = input.nextDouble();
System.out.println("Enter the time.");
time = input.nextDouble();
System.out.println("Distance equals: " + initialVelocity * time);
}
}
input.close();
}

关于java - 为什么我的代码会跳过 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823747/

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