This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 6 years ago.
I am a new user in java. As a programming exercise i have to make a program that - asks how many objects the user wants to create and then creates them. Class also calls for a class method that prints the number of created objects. also
to write the class which creates the objects. Class must be able to keep track of the number of created objects. Class also needs the method that prints the number of objects. Check the completed class for the names of the class and method.
I have tried following but have not reached any where so i am expecting some help: Please help!!
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
int count;
public void numberOfObjects(){
System.out.println(count);
}
}
}
You forgot 3 things:
1- to increment the count of the objects when they are created. You can do so in the Thing constructor.
2- declare the count variable as static to allow the variable to be shared between all objects of type Thing.
3 - to declare the numberOfObjects method as static since it is a class method that you are accessing via the Thing class
Try this:
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
private static int count = 0;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}
}
class Box
{
//Keep track of all your objects
Thing[] objs;
int cursor;
public Box(int countOfObjects)
{
objs = new Thing[countOfObjects];
}
//add new object to the array
public void add(Thing thing)
{
objs[cursor++] = thing
}
//gets the object
public Thing getThing(int pos)
{
if(pos < 0 || pos >= objs.lenght())
throw;
return objs[pos];
}
//count the objects
public int numberOfObjects()
{
System.out.println(objs.lenght());
return objs.lenght();
}
}
}
class Thing()
{
//any field you need to store
}
Your main should look like this
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Box box = new Box(amount);
for(int i = 0; i<amount; i++) {
box.Add(new Thing());
}
box.numberOfObjects();
}
Declare count as static and add count in constructor.Another import thing,move Thing class out of NumberOfObjects Class,otherwise, the Thing class is an inner class, you will need create NumberOfObjects instance first and use this object to create Thing instance.
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
}
class Thing{
private static int count ;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}
Related
I am making a program with two classes, one to create methods and the other as the tester class. I am having difficulties assigning the input to a new variable, which needs to be used to invoke the methods from the other class.
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int obj = new NumberUtility(0);
System.out.println("Enter a number. Enter 0 to end");
obj = scan.nextInt();
As example here is the beginning of the other class
public class NumberUtility {
int n = 0;
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
public int getN() {
return n;
}
public boolean isEven() {
if((n % 2 == 0)) {
return true;
} else
return false;
}
My code is incomplete elsewhere but that is the main issue I have been trying to work around. Since if I set it to an int, it won't work. Sorry if this is a stupid question, I am new to java coding.
With this line:
int obj = new NumberUtility(0);
you are attempting to assign a new NumberUtility object to the variable obj which is of type int. You cannot do that! That's like trying to create a doghouse, and then shoving your dog into a birdhouse. They're just not compatible.
As well, later, you try to reassign obj to the result of scan, which would work, but probably not what you want, as obj is still an int:
obj = scan.nextInt();
I think what you want to do is something like the following:
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Enter a number. Enter 0 to end");
// Read a number from the scanner
int number = scan.nextInt();
// Create a new NumberUtility from this primitive integer
NumberUtility obj = new NumberUtility(number);
System.out.println("Even? " + obj.isEven());
By the way, you can simplify your isEven method as well:
public boolean isEven() {
return (n % 2 == 0);
}
Edit: I see I'm not done yet.
In the NumberUtility class, you have defined a constructor for the class:
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
This seems like an odd thing to do. You are ignoring the input (int n) and then calling all the methods of the class which don't really do much.
I think you want your constructor to be something like this:
public NumberUtility(int input_n) {
// Save the constructor's input parameter to the member field 'n'
this.n = input_n;
}
Hy my method is this:
public static String[] getcontestants(String[] contestants) {
int numcontestants = 8;
String name[] = new String[numcontestants];
for (int j = 0; j < numcontestants; j++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j] = ip.nextLine();
}
return name;
}
I would like to call this method in the static void main but I don't exactly know how to do it. Tell me if there's any mistake in this method. Thanks!
So tbh, I like Maarten Bodewes's answer better, but I think this might be a bit easier for you to understand.
Main :
public static void main(String[] args) {
String[] contestants = getcontestants();
}
I edited Your function just a bit:
public static String[] getcontestants()
{
int numcontestants=8;
String name[] = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j]=ip.nextLine();
}
return name;
}
Hope that answers your question!
You can just use
MyClass.getcontestants(new String[] { "MS", "MR" });
where MyClass is the class that contains the method. You can leave out MyClass. if your main method is in the same MyClass class.
This is a direct answer to your question. If you look at the design of your class then Hadeems answer shows you that you don't need to pass the String array to the method; the scanner can be used locally.
You don't need to create scanner object in this method (it will create as many objects as the loop goes which is not the standard way of coding & not efficient at all).
Declare static Scanner ip = new.... ; outside the method within a class as global variable. (static - so that it's only one instance)
class YourClassName{
static Scanner ip = new....;
public static void main(String [] args){
//String[] inputStringArray = getcontestants( //new String (){"my", "text", "as", "string", "array"});
// Why passing string array to the function where actually you are taking input from user
// Better don't pass anything except length of the string array
String[] inputStringArray = getcontestants(contestanstCount);
}
public static String[] getcontestants(..){}
}
here is the code. Try it.
import java.util.Scanner;
public class AmadouQuestion {
public static void main(String[] args) {
String [] names = getcontestants(3);
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
public static String[] getcontestants(int numcontestants)
{
Scanner ip=new Scanner(System.in);
String[] names = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
System.out.println("Enter contestant's name");
names[j]=ip.nextLine();
}
ip.close();
return names;
}
}
I am trying to find a way to assign values to an Array from the scanner input by using enhanced For loop. But I don't see a way I can do it.
In the code below i have declared a getInput() method which loops through the Array and assign numbers from the scanner input. But in case of enhanced For loop I can't really use something like this -
For(int i: baseData){
//basedata[i]=scanner.nextInt()}
because baseData array will not return any value as it iterates, so i thought how about iterating through scanner.nextInt() and assign values in the array, but scanner.nextInt() is not a array.
So what could the easy solution for this problem?
package com.ksk;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
for (int i = 0; i < baseData.length; i++) {
baseData[i] = scanner.nextInt();
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
A for-each loop hides the iterator, so you won't be able to update the array with one (at least not without adding a new counter / iterator). Instead, assuming you're using Java 8+, you can write an IntStream generator using your Scanner. Something like,
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
However, this is really just an example, in real life I would prefer code that is a little more forgiving with unexpected input.
Try like this.
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
printInput();
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
OR
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
int position =0;
for(int i:baseData){
baseData[position] = scanner.nextInt();
position++;
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
}
}
import java.util.Scanner;
public class takeAGuess {
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
public class board {
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
}
I already tried these lines:
new[] board = board.Createboard();
int board[] = board.Createboard();
{
int board = new board();
board = createBoard();
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes therefore I create lots of them.
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
where is playboard defined?
And... so much classes! Use methods in the Main class instead, it'll make your job lighter.
I am pretty new at Java and I am finding difficulty in solving the problem. Basically the code get a number, and generate a vector in the function generateVector. When I run this code, I am asked to put a number and then the software stay running forever. If possible, could you guys help me without other functions that is kind advanced? I am still learning. Thanks.
import java.util.Scanner;
public class Atividade02 {
static Scanner dados = new Scanner(System.in);
static int n;
//Main
public static void main(String args[]){
System.out.println("Type a number: ");
n = dados.nextInt();
int[] VetorA = generateVector(n);
for(int i=0; i<VetorA.length; i++){
System.out.println("Position: "+ VetorA[i]);
}
}
//Função
public static int[] generateVector(int n){
int[] VetorA = new int [n];
for (int i=0; i<n; i++){
VetorA[i] = dados.nextInt();
}
return VetorA;
}
}
I am asked to put a number and then the software stay running forever.
Did you enter in the n numbers required by generateVector? The program is probably just blocked on input from the user.
Try to modfiy the class as follows:
import java.util.Scanner;
public class Atividade02 {
// Added private access modifiers for properties.
// It's not necessary here, but as a general rule, try to not allow direct access to
// class properties when possible.
// Use accessor methods instead, it's a good habit
private static Scanner dados = new Scanner(System.in);
private static int n = 0;
// Main
public static void main(String args[]){
// Ask for vector size
System.out.print("Define vector size: ");
n = dados.nextInt();
// Make some space
System.out.println();
// Changed the method signature, since n it's declared
// as a class (static) property it is visible in every method of this class
int[] vetorA = generateVector();
// Make some other space
System.out.println();
// Show results
for (int i = 0; i < vetorA.length; i++){
System.out.println("Number "+ vetorA[i] +" has Position: "+ i);
}
}
// The method is intended for internal use
// So you can keep this private too.
private static int[] generateVector(){
int[] vetorA = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Insert a number into the vector: ");
vetorA[i] = dados.nextInt();
}
return vetorA;
}
}
Also when naming variables stick with the Java naming convention, only classes start with capital letters.