首页 > 解决方案 > 如何在扫描仪中正确使用多个字符串变量?

问题描述

我是 Java 新手。我想我在扫描仪中错误地使用了字符串变量

我的代码

import java.util.Scanner;

public class AgeNextYear{
   public static void main (String[ ] args){
   
      String userName;
      int age; 
      String city;
    
      
      Scanner scan = new Scanner(System.in);
      
      System.out.println("What is your name?");
      userName = scan.nextLine();
      
      
      System.out.println("How old are you " + userName + "?");
      age = scan.nextInt();
      
      System.out.println("Which city do you live in?");
      city = scan.nextLine();
            
      System.out.println("Hello " + userName + " ,you are " + age + " and you live in " + city + ". Next year you will be " + (age + 1) + ".");
      
      }
  }
  

输出

What is your name?

Mark

How old are you Mark?

34

Which city do you live in?

Hello Mark ,you are 34 and you live in . Next year you will be 35.

如何修复我的代码,以便不跳过城市的用户输入?

标签: java.util.scanner

解决方案


要解决此问题,请使用.next()而不是.nextLine(). 这是因为您的城市扫描仪上方已经有一个.nextLine()(名称扫描仪)。这是最终的代码(有效):

import java.util.Scanner;
public class test{
   public static void main (String[ ] args){
      String userName;
      int age; 
      String city;
      Scanner scan = new Scanner(System.in);      
      System.out.println("What is your name?");
      userName = scan.next();
      System.out.println("How old are you " + userName + "?");
      age = scan.nextInt();
      System.out.println("Which city do you live in?");
      city = scan.next();
      System.out.println("Hello " + userName + " ,you are " + age + " and you live in " + city + ". Next year you will be " + (age + 1) + ".");
      }
  }

推荐阅读