繁体   English   中英

使用用户输入来调用整数

[英]Using user input to call an integer

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



  }

}

作为一个初学者,您可能想使用一个简单的HashMap ,它将这些映射存储为键,值对。 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)); //  
  }    
}

输出:
请输入您的名字:约翰
你欠我:5

如果要以字符串形式读取用户输入,则最好使用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");
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM