使用用户输入来调用整数

时间:2015-09-21 04:10:01

标签: java int java.util.scanner

我是编码的初学者,我正在尝试创建一个简单的程序,当读者输入他们的名字时,该程序会显示他们欠多少钱。我在考虑使用Scannernext(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. 



  }

}

2 个答案:

答案 0 :(得分:3)

作为初学者,您可能希望使用简单的HashMap,它会将这些映射存储为键,值对。 Keynamevalue将为money。这是一个例子:

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)); //  
  }    
}

输出:
请输入您的名字:John 你欠我的是:5

答案 1 :(得分:0)

如果您希望将用户输入读取为String,那么使用nextLine()方法将是一个好主意。

您还需要创建一个方法,该方法接受String参数,即名称并返回欠款。

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");
        }