【问题标题】:Using user input to call an integer使用用户输入调用整数
【发布时间】:2015-09-21 04:10:01
【问题描述】:

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



  }

}

【问题讨论】:

  • 创建一个 映射并根据名称(作为键)检索 int(值)。

标签: java int java.util.scanner


【解决方案1】:

作为初学者,您可能想使用一个简单的HashMap,它将这些映射存储为key, value 对。 Key 将是 namevalue 将是 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。有用的解决方案
【解决方案2】:

如果您希望将用户输入作为字符串读取,那么使用 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");
        }

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2018-06-08
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多