Java 使用用户输入调用整数

Java 使用用户输入调用整数,java,int,java.util.scanner,Java,Int,Java.util.scanner,我是一名编码初学者,我正在尝试创建一个简单的程序,当读者输入他们的名字时,程序会显示他们欠了多少钱。我正在考虑使用扫描仪、next(String)和int import java.util.Scanner; public class moneyLender { //This program will ask for reader input of their name and then will output how much //they owe me. (The amount t

我是一名编码初学者,我正在尝试创建一个简单的程序,当读者输入他们的名字时,程序会显示他们欠了多少钱。我正在考虑使用
扫描仪
next(String)
int

import java.util.Scanner;

public class moneyLender {
  //This program will ask for reader input of their name and then will output how much 
  //they owe me. (The amount they owe is already in the database)

  public static void main(String[] args) {

    int John = 5; // John owes me 5 dollars
    int Kyle = 7; // Kyle owes me 7 dollars

    //Asking for reader input of their name
    Scanner reader = new Scanner(System.in);
    System.out.print("Please enter in your first name:");
    String name = reader.next();

    //my goal is to have the same effect as System.out.println("You owe me " + John);
    System.out.println("You owe me: " + name) // but not John as a string but John 
                                              // as the integer 5

    //Basically, i want to use a string to call an integer variable with 
    //the same value as the string. 



  }

}

作为初学者,您可能希望使用一个简单的
HashMap
,它将这些映射存储为键、值对<代码>键将是
名称
将是
货币
。下面是一个例子:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class moneyLender {
  public static void main(String[] args) {

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("John", 5);
    map.put("Kyle", 7);

    Scanner reader = new Scanner(System.in);
    System.out.print("Please enter in your first name:");
    String name = reader.next();

    System.out.println("You owe me: " + map.get(name)); //  
  }    
}
import java.util.HashMap;
导入java.util.Map;
导入java.util.Scanner;
公共级放债人{
公共静态void main(字符串[]args){
Map Map=newhashmap();
地图放置(“约翰”,5);
地图放置(“凯尔”,7);
扫描仪阅读器=新扫描仪(System.in);
System.out.print(“请输入您的名字:”);
字符串名称=reader.next();
System.out.println(“你欠我的:+map.get(name));//
}    
}
输出:
请输入您的名字:John

您欠我:5

如果您想将用户输入读取为字符串,那么最好使用nextLine()方法

您还需要创建一个方法,该方法采用字符串参数,即名称并返回欠款

public int moneyOwed(String name){      
       switch(name){

case "Kyle": return 5;

case "John": return 7;

    }
}

    public static void main(String[] args) {

        int John = 5; // John owes me 5 dollars
        int Kyle = 7; // Kyle owes me 7 dollars


        Scanner reader = new Scanner(System.in);
        System.out.print("Please enter in your first name:");
        String name = reader.nextLine();


        System.out.println(name +" owes me " + moneyOwed(name) + " dollars");
        }

创建一个映射并基于名称(作为键),检索int(值)。我不知道映射,谢谢+1。有用的解决方案