gpt4 book ai didi

java - 如何结束 if 并移至另一行

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

当我想查看条件然后移动到另一行但java中没有“goto”时,我的问题就开始了,所以我不知道如何从这个if内部移动并转到下一行当我在后面输入 return 时,它不会运行代码......如果你们能帮助我解决这个问题,我将不胜感激......源代码在这里:::

  //package CaloriesCalculator
import java.util.Scanner;

class Main {
// @SuppressWarnings("null")
@SuppressWarnings("resource")
public static void main(String[] args) {
// Initiate a new Scanner
// here I have tried to use scanner
boolean run = true;
while(run){
@SuppressWarnings("resource")
Scanner userInputScanner = new Scanner(System.in);


System.out.print("\nIf you are Male Press 1, If you are Female Press 2 ");

int G = userInputScanner.nextInt();

if(G == 1)

{
System.out.print("Please Enter your Weight..");
int W = userInputScanner.nextInt();

if((W <300) && (W > 1)) {//error message


// my problems start here !! I need to have the next input here but it doesn't work



}
System.out.print("Please Enter your Weight..");
W= userInputScanner.nextInt();
return;
// int m;
System.out.print("Please Enter your Height");
int H = userInputScanner.nextInt();
System.out.print("Please Enter your Age..");
int A = userInputScanner.nextInt();

double BMR = 10*W + 6.25*H - 5*A +5 ;

if( BMR > 0) {System.out.print(" Your body needs the amount of calories : "+ BMR );}

else { System.out.print("Do you know you are a mess ? " );}





//int H = userInputScanner.nextInt();



// else {System.out.print("Please Enter valid weight");}
}

else if(G == 2)

{

System.out.print("Please Enter your Weight..");
int W = userInputScanner.nextInt();

System.out.print("Please Enter your Height");
int H = userInputScanner.nextInt();

System.out.print("Please Enter your Age..");
int A = userInputScanner.nextInt();

double BMR = 10*W + 6.25*H - 5*A -161 ;


if(BMR > 0)
{
System.out.print(" Your body needs the amount of calories : "+ BMR );
}

else
{
System.out.print("Do you know you are a mess ? " );

}


}
else
{
System.out.print(" Please put the right number or don't use program " );
}
}

}

}

最佳答案

nextInt()方法doesn't read the whole line (with carriage return and line feed) ,因此,当您重新读取 nextInt() 时,您会得到一个空字符串,这就是您的 if 不执行其中代码的原因。

你必须:

  1. 首先使用nextLine()读取整行。

  2. 使用Integer.parseInt()方法验证整数输入。

换句话说:

Scanner userInputScanner = new Scanner(System.in);
String s = userInputScanner.nextLine();

try{
Integer.parseInt(s);
}
catch(NumberFormatException ex){
System.out.println("Its not a valid Integer");
}

否则,您可以执行 nextInt(),然后执行 nextLine() 来使用 \n:

int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)

关于java - 如何结束 if 并移至另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26483343/

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