我试图打印“fields”的整个值。但它跳过了第一个输入,为什么?

huangapple go评论102阅读模式
英文:

I'm trying to print whole value of "fields." But it skips the first input, why?

问题

Sure, here is the translated code:

import java.util.Scanner;

public class ElseIf {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
        System.out.println("输入姓名");
        String a = s.next();
        System.out.println("输入学号");
        int b = s.nextInt();
        System.out.println("输入兴趣领域");
        s.next();//消耗ENTER键留下的'\n',nextInt()不能消耗它
        String c = s.nextLine();
        System.out.println("嗨,我的名字是" + a + ",我的学号是" + b + "。我的兴趣领域是" + c + "。");
    }
}

输出:

输入姓名
Subhadip
输入学号
21
输入兴趣领域
music, dance
嗨,我的名字是Subhadip,我的学号是21。我的兴趣领域是 dance。

它不会打印出 "music"。

英文:
import java.util.Scanner;
public class elseif {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	
		  Scanner s = new Scanner(System.in);
		    System.out.println("Enter name");
		    String a = s.next();
		    System.out.println("Enter roll number");
		    int b = s.nextInt();
		    System.out.println("Enter Filed of interest");
		    s.next();//To consume '\n' left by ENTER KEY, it is not consumed by nextInt()
		    String c = s.nextLine();
		    System.out.println("Hey, my name is "+a+" and my roll number is "+b+". 
                                My field of interest is "+c+".");
		  }
		}

Output:

Enter name
Subhadip
Enter roll number
21
Enter Filed of interest
music, dance
Hey, my name is Subhadip and my roll number is 21. My field of interest is dance.

It doesn't print "music."

答案1

得分: 0

你不需要使用 s.next();,你可以使用 Integer.parseInt(s.nextLine()); 来获取 b

Scanner s = new Scanner(System.in);
System.out.println("输入姓名");
String a = s.nextLine();
System.out.println("输入学号");
int b = Integer.parseInt(s.nextLine());
System.out.println("输入兴趣领域");
String c = s.nextLine();
System.out.println("嗨,我的名字是" + a + ",我的学号是" + b + "。我的兴趣领域是" + c + "。");
英文:

You don't need s.next(); you can use Integer.parseInt(s.nextLine()); to get b

Scanner s = new Scanner(System.in);
System.out.println("Enter name");
String a = s.nextLine();
System.out.println("Enter roll number");
int b = Integer.parseInt(s.nextLine());
System.out.println("Enter Filed of interest");
String c = s.nextLine();
System.out.println("Hey, my name is "+a+" and my roll number is "+b+". My field of interest is "+c+".");

huangapple
  • 本文由 发表于 2020年7月31日 23:51:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63195117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定