gpt4 book ai didi

java - 此代码不接受性别输入,而是直接接受城市的最后输入

转载 作者:行者123 更新时间:2023-12-01 17:42:04 26 4
gpt4 key购买 nike

import java.util.Scanner;

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

System.out.println("Enter your name");
String n=sc.nextLine();

System.out.println("Enter your age");
int age=sc.nextInt();

System.out.println("Enter your gender");
String g=sc.nextLine();

System.out.println("Hailing From");
String c=sc.nextLine();

System.out.println("Welcome, " +n+ "!");
System.out.println("Age:" +age);
System.out.println("Gender:" +g);
System.out.println("City:" +c);
}
}

代码不接受性别输入。不知道代码有什么问题?

最佳答案

当你得到nextInt时,你仍然需要走到行尾。请尝试以下操作:

import java.util.Scanner; public class Main {

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

System.out.println("Enter your name");
String n=sc.nextLine();

System.out.println("Enter your age");
int age=sc.nextInt();
sc.nextLine(); //YOU NEED TO ADD THIS LINE!

System.out.println("Enter your gender");
String g=sc.nextLine();

System.out.println("Hailing From");
String c=sc.nextLine();

System.out.println("Welcome, " +n+ "!");
System.out.println("Age:" +age);
System.out.println("Gender:" +g);
System.out.println("City:" +c);
}}

关于java - 此代码不接受性别输入,而是直接接受城市的最后输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60935328/

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