Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am teaching myself Java from books and videos from internet.
i know the bellow code is wrong but how can I make object name read from a variable like this?
public static void main(String[] args) {
Scanner input =new Scanner (System.in);
String ObjectName=input.next();
className ObjectName=new className ();
ᴋᴇʏsᴇʀ , Pshemo ,Brian Vanover i edit my question
i have class named BankAccount and another main class with this code
public static void main(String[] args) {
Scanner input =new Scanner (System.in);
System.out.println("Please Enter ID");
int id=input.nextInt();
System.out.println("Please Enter Name");
String name = input.next();
System.out.println("Please Enter Balance");
double balance = input.nextDouble();
String client=input.next();
BankAccount client = new BankAccount (id,name,balance);// i know this code line is worng
client.printStatement();
If you are asking how to create instance of class based only on class name then you can try with
Scanner input =new Scanner (System.in);
String className = input.nextLine();
Class<?> clazz = Class.forName(className);
Object o = clazz.newInstance();
Now if you pass full.package.name.of.YourClass and if this class has accessible no-argument constructor you should be able to create its instance via newInstance method.
Edit.
It seems that you want to store your object on some name provided by user. You can't do that explicitly as variable name, but you can make some map from String to yourObject using Map interface. Your code can look like
Scanner input = new Scanner(System.in);
System.out.println("Please Enter ID");
int id = input.nextInt();
System.out.println("Please Enter Name");
String name = input.next();
System.out.println("Please Enter Balance");
double balance = input.nextDouble();
String client = input.next();
BankAccount clientAccount = new BankAccount(id, name, balance);
client.printStatement();
Map<String,BankAccount> map = new HashMap<>();
map.put(client, clientAccount);
later you can just get account of client by using map.get and get account details like
map.get(client).getID();//assuming that you have getter for ID
This can be handled by using an enum or if-logic If-logic will be ok if you expect a limited number of possible inputs:
public static void main(String[] args) {
Scanner input =new Scanner (System.in);
String objectName = input.next();
if (ObjectName.equals("obj1")) {
Obj1 myObject = new Obj1();
} else {
Obj2 myObject = new Obj2();
}
First file name Out.java & second file name in.java
//first file's code start here
public class Out {
public static void main(String[] args) {
in inObject =new in();
inObject.ikl();
}
}
//second file's code start here
import java.util.Scanner;
public class in {
public static int ikl() {
Scanner input=new Scanner(System.in);
int j=input.nextInt();
System.out.println(j);
return j;
}
}
Related
So I am using eclipse to practice coding using java and till now it was doing great, until I wrote this program:
import java.util.*;
public class cars {
String name;
int dom;
Scanner in = new Scanner(System.in);
void takedata()
{
name=in.next();
dom=in.nextInt();
}
void displaydata()
{
System.out.print("Enter the name of the car"+name);
System.out.print("Enter the Date of Manufacture of the car"+dom);
}
public static void main(String[] args)
{
cars x = new cars();
cars y = new cars();
cars z = new cars();
x.takedata();
y.takedata();
z.takedata();
x.displaydata();
y.displaydata();
z.displaydata();
}
}
whenever I am trying to run the code it is showing me nothing.
I need help.
It wont show anything. Your code will wait till you enter the care name. So, first you need to provide input as your takeData() method is getting called before displayData(). Modify your takeData() method as shown below:
void takedata()
{
System.out.println("Enter Name of the Car: ");
name=in.next();
System.out.println("Enter Date of Manufacture: ");
dom=in.nextInt();
}
Then after executing your program your will be able to see below message:
Enter Name of the Car:
I am very new in programming into Java.
My question is that I have a code (see below) and I want to compare them with if statement. An errors occur at line 9 (string test) and 11(if(test.equals). I completely do not have idea.
I have made a code with int and it works perfect, but that.
package bucky;
import java.util.Scanner;
class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
if (test.equals("YES")) {
System.out.println("YES");
} else {
System.out.println("TIS IS ELSE");
}
}
}
You are almost there... define YES as string and that it
String test = sc.nextLine();
String YES = "yes";
if (test.equals(YES)) {
or even better use equalsIgnoreCase() so you can get rid off the case sensitive input
if (test.equalsIgnorecase(YES))
So I have this assignment, and it says to create a arraylist using standard input, and constantly prompt the user for commands. Now, I understand how to add commands, WITHIN the code, but I dont understand how to take what the user puts in, and turn that into a command in the arraylist. Here's what I got so far:
import java.util.*;
import java.util.Scanner;
public class assignment216{
public static void main (String args[]){
ArrayList<String> names = new ArrayList<String>();
Scanner s = new Scanner(System.in);
Scanner n = new Scanner(System.in);
System.out.println("Enter a command:");
String command = s.nextLine();
System.out.println("If you entered 'add', then enter a name:");
String input = n.nextLine();
}
}
EDIT New Code:
import java.util.*;
import java.util.Scanner;
public class assignment216{
public static void main (String args[]){
ArrayList<String> names = new ArrayList<String>();
Scanner e = new Scanner(System.in);
System.out.println("Enter command, or type 'quit' to exit");
String quit = e.next();
boolean exit = quit;
if(exit = true){
System.exit();
}
}
}
You can request that the user types in his commands and then check using the method from the String class equalsIgnoreCase() and compare it and see if it is the same as add, remove, etc. (whatever commands you need). Use if-else statements to implement the logic. For example if user input resolves to add, then you add an element. If user input is not any of the common functions, then print message that there was an error and so on. I cannot type out the answer in code as this is an assignment.
import java.util.*;
import java.util.Scanner;
public class assignment216{
public static void main (String args[]){
ArrayList<String> names = new ArrayList<String>();
Scanner e = new Scanner(System.in);
System.out.println("Enter command, or type 'quit' to exit \n");
while (!e.nextLine().equalsIgnoreCase("quit")) { // As long as input not equal to quit
if (e.nextLine().equalsIgnoreCase("add") {
System.out.println("Enter name to add:\n");
String name = e.nextLine();
names.add(name);
}
if (e.nextLine().equalsIgnoreCase("remove") {
System.out.println("Enter name to remove:\n");
String name = e.nextLine();
names.remove(name);
}
}
if(e.nextLine().equalsIgnoreCase("quit"){
scanner.close();
System.exit();
}
}
}
Check out the add() method in the java.util.List interface. Might help.
Java Project
public ArrayShoppingList()
{
// initialise instance variables
super();
}
//public void addItem(int itemPosition,String item){
// super.add(itemPosition,item);
// }
public void addItem(){
System.out.println("Please enter the item you wish to enter into the shopping
List");
Scanner reader1 = new Scanner(System.in);
String item = reader1.next();
super.add(super.size(),item);
}
public void getPosition(){
System.out.println("Please enter the item name that you wish to find
theposition of");
Scanner reader1 = new Scanner(System.in);
String item = reader1.next();
super.indexOf(item);
}
public void removeItem(){
System.out.println("Please enter the item number that you wish to remove");
Scanner reader1 = new Scanner(System.in);
String item = reader1.next();
int itemIndex = super.indexOf(item);
super.remove(itemIndex);
}
I want to know how to test such methods in a Test Class that ask for user input.
The methods call other methods from an ArrayLinearList and pass data that the user has entered in. I want to create code that simulates what the user might enter in.
You can use frameworks like Mockito or Powermock to mock the Scanner. If the class then calls the Scanner for input, you can let your mock return some strings which will be handled as user input by your class. Your class will not see a difference between the "real" scanner and your mock implementation.
See also:
https://code.google.com/p/mockito/
https://code.google.com/p/powermock/
You can use System.setIn(InputSteam)
Here you can specify your own inputstream and add the input you want to it.
Use System.setIn for Unitesting Scanner. For example:
String input = "Your input data";
System.setIn(new ByteArrayInputStream(input.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
Output:
Your input data
If I have the two functions below.
How can I select the function that will be chosen?
I imagine there is either some form of statement to determine the content of the scanner and therefore only have one function. Or it would be something that is passed to the function.
public static int questionAsk(String question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question+"\n");
System.out.print ("Answer: ");
return scan.nextInt();
}
public static String questionAsk(String question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question+"\n");
System.out.print ("Answer: ");
return scan.nextLine();
}
There is no way for the compiler to know which one of those methods you are calling. You could make it type safe by changing the String Types to something else, like this:
public static int questionAsk(IntQuestion question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question.toString() +"\n");
System.out.print ("Answer: ");
return scan.nextInt();
}
public static String questionAsk(StringQuestion question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question.toString() +"\n");
System.out.print ("Answer: ");
return scan.nextLine();
}
And adding two new classes:
public class IntQuestion extends String{
public IntQuestion(String question){
super(question);
}
}
public class StringQuestion extends String{
public StringQuestion(String question){
super(question);
}
}
When you construct an IntQuestion of StringQuestion, you can simply construct them the same way you would construct a String if you called the constructor:
IntQuestion intQuestion = new IntQuestion("Some String Here");
This is just a little bit of syntactic sugar to get the compiler to play nice and select the correct method based on the type.
I hope this helps.
You should first scan, parse and then call the required function using if else or switch case.
What you are doing right now is using the same code in two functions, and not reusing the code. Just use a single scan instead