Using a user input to make an object in Java - object

Is there a way for me to take a string input from scanner and create a new object with that string entry? Such as:
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String name = input.nextLine();
ListOfNames name = new ListOfNames();
}
Note that in the last line the "ListOfNames name = new ListOfNames();" I want the new object to be the string that the variable "name" holds.
I want to do this so that after the object is made I can add it to an array then be able to search the array later after inputting multiple names in for the one I need.
There is probably a way to do this with the arrays class but I am new and unfimliar with the class. Any help would be fantastic! Thanks!

You could do...
public class Test {
public static void main(String[] args) {
ArrayList<String> listOfNames = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String name = input.nextLine();
listOfNames.add(name);
}
Just add the received input from Scanner to listOfNames array list.
Or if you are really need to use another Object...
public class Name {
String value;
public Name(String value) {
this.value = value;
}
}
public class Test {
public static void main(String[] args) {
ArrayList<Name> listOfNames = new ArrayList<Name>();
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String nameValue = input.nextLine();
Name n = new Name(nameValue);
listOfNames.add(n);
}

Related

Using Scanner to take input from two objects of the same class

I have a problem with functionality of my simple program I am making at the moment. I am trying to create two objects, each of them is asking user to provide a name and then choose from few options, by using Scanner. First object, monster of class createMonster, is asking user to provide information through Scanner. However, while creating second object monster2 of class createMonster, program does not asking for user input.
Do I need to do some changes in my class CreateScanner or is it a bigger problem?
public class MainClass {
public static void main(String[] args) {
RandomMonsterGenerator monster = new RandomMonsterGenerator();
monster.createMonster();
RandomMonsterGenerator monster2 = new RandomMonsterGenerator();
monster2.createMonster();
}
}
RandomMonsterGenerator code:
public class RandomMonsterGenerator {
// Objects
Attributes attr = new Attributes();
CreateScanner createScanner = new CreateScanner();
// Variables
String monsterName;
String attributesValues;
int choice;
// Main method for generating monster
public void createMonster() {
attr.generateAttributes();
generateName();
chooseClass();
System.out.println("Generating random stats:");
attributesValues = attr.toString();
System.out.println(attributesValues);
createScanner.closeScanner();
}
// Generating monster name
private void generateName() {
System.out.println("Name your monster: ");
monsterName = createScanner.stringInput();
System.out.println("Name of the monster: " + monsterName);
}
// Choosing a class
private void chooseClass() {
System.out.println("Class descriptions: ");
System.out.println("Warrior has +2 to Strength and +2 to Condititon.");
System.out.println("Thief has +2 to Dexterity and +2 to Charisma.");
System.out.println("Mage has +2 to Intelligence and +2 to Wisdom.");
System.out.println("**************************************************");
System.out.println("Choose your class from following options: ");
System.out.println("Warrior, press '1'");
System.out.println("Thief, press '2'");
System.out.println("Mage, press '3'");
choice = createScanner.intInput();
switch(choice) {
case 1:
Warrior warrior = new Warrior(attr);
System.out.println(monsterName + " is a warrior.");
break;
case 2:
Thief thief = new Thief(attr);
System.out.println(monsterName + " is a thief.");
break;
case 3:
Mage mage = new Mage(attr);
System.out.println(monsterName + " is a mage.");
break;
default:
System.out.println("No option choosen.");
break;
}
}
}
CreateScanner code:
import java.util.Scanner;
public class CreateScanner {
Scanner sc = new Scanner(System.in);
public String stringInput() {
String input = "";
if (sc.hasNextLine()) {
input = sc.nextLine();
}
return input;
}
public int intInput() {
int input2 = 0;
if (sc.hasNextLine()) {
input2 = sc.nextInt();
}
return input2;
}
public void closeScanner() {
sc.close();
}
}
Two things.
First, don't close the scanner until you're done with it. This closes the System.in
as well and as soon as you do that you won't be getting anymore input. This is why it just skips over the second RandomMonsterGenerator input.
Second, only create one Scanner and pass it to your RandomMonsterGenerator as an argument. This keeps things simple.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
RandomMonsterGenerator monster = new RandomMonsterGenerator(scanner);
RandomMonsterGenerator monster2 = new RandomMonsterGenerator(scanner);
}

How to print the area of a circle in another method

I am trying to print out the answer for the Area of a circle in the myPrint(); method but it keeps calculating zero why?
I did my calculations in the Math(); method that I created. I am very new at coding and would greatly appreciate the help.
Thanks
package Project1;
import java.util.Scanner;
public class Code1 {
static String myStr;
static double radius;
static double answer;
static double pie;
public static void main(String[] args){
Name();
Info();
Math();
myPrint();
}
public static void Name(){
Scanner input = new Scanner(System.in);
System.out.println("What Is Your Name");
myStr = input.nextLine();
}
public static void Info(){
Scanner input = new Scanner(System.in);
String myStr;
System.out.println("What is Your Phone Number");
myStr = input.nextLine();
System.out.println("What is Your Age");
myStr = input.nextLine();
System.out.println("What is Your Postal Code");
myStr = input.nextLine();
}
public static void Math(){
double radius,answer;
double pie = 3.14;
Scanner input = new Scanner(System.in);
System.out.println("What is the Area of the Circle");
radius = input.nextDouble();
answer = pie *(radius * radius);
}
public static void myPrint(){
System.out.print("The answer is:"+ answer);
}
}
You have the static variable answer, but you declare answer again in Math(), so when you assign answer equal to your calculation, that's not changing the global variable, but it's changing the local variable. When you print answer in myPrint(), the answer will be 0 because it will have been assigned a value of 0 by default.

HashMap for Student Object does not print objects of Student

import java.util.Scanner;
public class StudentMap extends Student{
public static void main(String[] args)
{
Student[] studentClass = new Student[2];
Scanner s1 = new Scanner(System.in);
for(int i=1;i<=studentClass.length;i++)
{
System.out.println("Enter name for "+i+"Student");
String studentName = s1.next();
System.out.println("Enter email for "+i+"Student");
String email = s1.next();
System.out.println("Enter phone number for "+i+"Student");
Integer num = s1.nextInt();
studentClass[i] = new Student();
studentClass[i].setName(studentName);
studentClass[i].setEmail(email);
studentClass[i].setPhoneNumber(num);
}
s1.close();
for(Student stu : studentClass)
{
System.out.println(stu.name);
System.out.println(stu.email);
System.out.println(stu.phoneNumber);
}
}
}
While executing this code it gives an error of OutOfBoundIndex ..
I have created Student class to which has all get set method for name, email and phoneNumber.

How to make FileHelpers set the line number on each record?

Are there any chances to have the MultiRecordEngine set the line number for each record?
I read the documentation and found that the Engine has a LineNumber property, but I couldn't find a way to use it.
What I would like to have:
i.e.:
[FixedLengthRecord]
public class Employee
{
public int LineNumber; // <-- setup by the engine while reading the file
[FieldFixedLength(1)]
public string Type = "2";
[FieldFixedLength(6)]
[FieldTrim(TrimMode.Left, "0")]
public int ID;
}
Or... can I rely on the index of the record in the collection created by the Engine.ReadFile?
i.e.:
static void Main(string[] args)
{
var engine = new MultiRecordEngine(CustomSelector, _types);
var obj = engine.ReadFile("order.txt");
// obj.GetValue(100) returns same record found on the 101th line in the file?
}
You can use the AfterReadRecord event to set the LineNumber property.
Here is a working example
public class Employee
{
[FieldIgnored]
public int LineNumber; // <-- setup by the engine while reading the file
[FieldFixedLength(1)]
public string Type = "2";
[FieldFixedLength(6)]
[FieldTrim(TrimMode.Left, "0")]
public int ID;
}
class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<Employee>();
engine.AfterReadRecord += engine_AfterReadRecord;
Employee[] records = engine.ReadString("2000003" + Environment.NewLine
+ "5000006");
Employee firstRecord = records[0];
Assert.AreEqual(1, firstRecord.LineNumber);
Assert.AreEqual("2", records[0].Type);
Assert.AreEqual(3, records[0].ID);
Employee secondRecord = records[1];
Assert.AreEqual(2, secondRecord.LineNumber);
Assert.AreEqual("5", records[1].Type);
Assert.AreEqual(6, records[1].ID);
Console.Read();
}
static void engine_AfterReadRecord(EngineBase engine, AfterReadEventArgs<Employee> e)
{
e.Record.LineNumber = engine.LineNumber;
}
}

Get property values from a string using Reflection

I am new to this concept of reflection and finding problem in retrieving property value from a string. E.g.
I have a class Employee with following properties :
public string Name {get;set;}
public int Age {get;set;}
public string EmployeeID {get;set;}
string s = "Name=ABCD;Age=25;EmployeeID=A12";
I want to retrieve the value of each property from this string and create a new object of Employee with those values retrieved from the string for each field.
Can anyone please suggest how it can be done using reflection ??
//may be..
string s = "Name=ABCD;Age=25;EmployeeID=A12";
string[] words = s.Split(';');
foreach (string word in words)
{
string[] data = word.Split('=');
string _data = data[1];
Console.WriteLine(Name);
}
Here an example of how you maybe could do it
it used Reflection like you wanted ^^
using System;
using System.Collections.Generic;
using System.Reflection;
namespace replace
{
public class Program
{
private static void Main(string[] args)
{
var s = "Name=ABCD;Age=25;EmployeeID=A12";
var list = s.Split(';');
var dic = new Dictionary<string, object>();
foreach (var item in list)
{
var probVal = item.Split('=');
dic.Add(probVal[0], probVal[1]);
}
var obj = new MyClass();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(dic[property.Name]);
if (property.PropertyType == typeof(Int32))
property.SetValue(obj, Convert.ToInt32(dic[property.Name]));
//else if (property.PropertyType== typeof(yourtype))
// property.SetValue(obj, (yourtype)dic[property.Name]);
else
property.SetValue(obj, dic[property.Name]);
}
Console.WriteLine("------------");
Console.WriteLine(obj.Name);
Console.WriteLine(obj.Age);
Console.WriteLine(obj.EmployeeID);
Console.Read();
}
}
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
public string EmployeeID { get; set; }
}
}

Resources