简体   繁体   中英

How to change the input from a String to a scanner input and then use it in my code

For my final project, I am attempting to change the input in the tester class from a string to a scanner input

Here is the original line of code:

public class FinancialCalculatorTester
{
    public static void main(String[] args)
   {
       FinancialCalculator.showCustomerInfo("Antonio Williams");
   }
}

The output comes to this:

Name: Antonio Williams
Age: 40
Phone: (225)897-7865
Salary: 85043.0
Insurance: 2084.0
Monthly Expenses: 10000.0
Savings: 72959.0

(The information comes from the other class with all the information)

I would like to change it to something along the lines of:

import java.util.Scanner;

public class FinancialCalculatorTester {

    public static void main(String[] args) {
        System.out.println("Enter name: ");
        Scanner input = new Scanner(System.in);           
        FinancialCalculator.showCustomerInfo();
     }
 }

I want to do this because there is more than one name in the Array list and I want the user to choose what name they want. If needed, I can show the code for the other class.

I want to choose a name from the other class and get an output of that names information (such as the original output seen above.) Each name has their own output such as that one. Thank you!

import java.util.Scanner;

public class FinancialCalculatorTester {

public static void main(String[] args) {
    System.out.println("Enter name: ");
    Scanner input = new Scanner(System.in);
    System.out.println(FinancialCalculator.showCustomerInfo(input.nextLine()));       
 }
}

You mean this?

EDIT: You have to log the result of showCustomerInfo, assuming that this method returns a String with all the info mentioned.

Hint: Spend some time reading the JSE API pages.

TLDR:

  1. You can construct a Scanner object with an InputStream parameter.
  2. Browsing the InputStream API page shows that there is a ByteArrayInputStream class.

Construct a ByteArrayInputStream from the String value then construct a Scanner from the ByteArrayInputStream.

The above is the result of a, likely, bad assumption on my part.

Go with what DogyCodeException suggests and construct the Scanner using the String as a constructor argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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