How to use the the count number somewhere else in java - java

Is there anyway in which I can place count into a variable. E.g. I have Count to count the number of lines. After that I want to use the number that the count has provided, and then add this number in a variable that can be used somewhere else, e.g. to add with another number, or find an percentage or to create a pie chart using the number.
public void TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()){
count++;
file.nextLine();
}
System.out.println(count);
file.close();
I want to use the number that I will get in count, and use it somewhere else (e.g another method), but I have no idea how to do that.
Thank you.

Firstly I recommend that you should complete this javatutorial if you new to programming.
If you define it in class as a global variable(as an attribute of class) out of method, you can use it in every method in your class.
But if your question about to using it in everywhere of the project within different class, you can use singleton design pattern;
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null)
{
instance = new ClassicSingleton();
}
return instance;
}
}

EDIT
Make a getter method for count variable.
E.g.
public class Test {
private int count = 0;
public void method1(){
while(file.hasNext()){
count++;
file.nextLine();
}
System.out.println(count);
}
public void method2(){
System.out.println(count);
}
public int getCount(){
return count;
}
}

Just return the value in the method you created:
public class Test {
public int TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()) {
count++;
file.nextLine();
}
System.out.println(count);
file.close();
return count;
}
public static void main(String[] args) {
Test t = new Test();
int testCount = TotalCount12();
}
}

Related

Using for loop increments in a method

I am trying to use a method to print a random number multiple times using increments. The problem is I don't seem to understand methods very well. I have no problem doing it otherwise but when I try to do it by calling a method I can't get any return and my console just remains blank. Here is what I have so far:
package WayBack;
import java.util.Random;
public class Review {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
{
method1();
}
public String method1()
{
String rv = "";
for(int i = 0; i <= 4; i++)
{
Random r = new Random();
int number = r.nextInt((100) - 0) * 100;
System.out.println("your number is " + number);
}
return rv;
}
}
Any help would be much appreciated
Thank You
You need to invoke the method1 function in main. But your method1 function is an instance method. So you should new an Instance of the Review class, and then invoke the method1 function.
public static void main(String[] args) {
// TODO Auto-generated method stub
Review instance = new Review();
instance.method1();
}
Or, You can declare the method1 as static so that you can call it directly in the main method.
public static void main(String[] args) {
// TODO Auto-generated method stub
method1();
}
public static String method1()
{
String rv = "";
for(int i = 0; i <= 4; i++)
{
Random r = new Random();
int number = r.nextInt((100) - 0) * 100;
System.out.println("your number is " + number);
}
return rv;
}
An other way, you can invoke the method1 in the constructor of the Review class. And If you create an instance of a class, the methods in the constructor of the class are automatically called. In this way, you don't have necessary to invoke your method in the main.
public static void main(String[] args) {
// TODO Auto-generated method stub
Review instance = new Review(); // it will call the method1 automatically
}
public Review() {
// invoke your method
method1();
}
In your code, you are not calling the method method1. It is not wrapped in Main, instead it is wrapped in a set of floating curly braces.
package WayBack;
import java.util.Random;
public class Review {
public static void main(String[] args) {
method1(); // put it here
}
// This block is not executed
{
method1();
}
public String method1()
{
String rv = "";
for(int i = 0; i <= 4; i++)
{
Random r = new Random();
int number = r.nextInt((100) - 0) * 100;
System.out.println("your number is " + number);
} return rv;
}
}
As everyone is pointing out, you need to include method1() inside your main.
The reason for this is because Java starts all programs in public static void main(String[] args) from here it reads one line at a time inside the block of code. A block of code is defined as what is in the '{' and '}', often called braces.
Because the main method is ALWAYS static, and you cannot reference non-static things inside a static method, you will either need to change your method1 to also be static or create an object that can reference the method. You will learn about this later on.
For now,
public static void main(String[] args) {
method1();
}
public static String method1() {
String rv = "";
Random r = new Random(); //this 'r' object only needs to be created once.
for(int i = 0; i <= 4; i++)
{
int number = r.nextInt(100) * 100; // you were subtracting 0 for no reason?
System.out.println("your number is " + number);
rv = rv + number + ", "; //rv is empty in your example, this will fill it with the 5 numbers generated. (It's not perfect)
}
return rv;
}
Your rv variable return an empty value.
You can create a class(MyClass) where in future you can Add other methods:
For example you can do:
package WayBack;
import java.util.Random;
public class Review {
public static void main(String[] args) {
// TODO Auto-generated method stub
public MyClass work=new MyClass();
work.method1();
}
}
//---create an other file and write this one
Public Class MyClass{
private String rv;
private int number;
private Random r;
//constructor
public MyClass(){
this.number=0;
this.rv="";
this. r= new Random();
}
public String method1() {
for(int i = 0; i <= 4; i++) {
number = r.nextInt((100) - 0) * 100;
System.out.println("your number is "+number);
rv=rv+number+","; }
return rv; }
}//end MyClass
Since 'method1' is called in a block, this will execute at the time when you create the object.
{
method1();
}
You only have to create the object in the main method. No need to make method static.
Try this,
public static void main(String[] args) {
// TODO Auto-generated method stub
Review review = new Review();
}

when a method should return a value java

I am a new user for java and I am a little confused on whether a method should return a value or not in java for example I wrote this simple method
public static void increase_user() {
int number=3;
if(number<10)
user++;
}
public static void main(String[] args) {
int user=10;
increase_user();
System.out.println(user);
}
Should I make increase_user method return a value in this case? and when it should return a value?
1.) You need to pass the user object.
2.) Also need to return the user object.
public static int increase_user(int user) {
int number = 3;
if (number < 10)
user++;
return user;
}
public static void main(String[] args) {
int user = 10;
user = increase_user(user);
System.out.println(user);
}
Making User variable static, works same as above, no need to pass/return user object
public class Test2 {
static int user = 10;
public static void increase_user() {
int number = 3;
if (number < 10)
user++;
}
public static void main(String[] args) {
increase_user();
System.out.println(user);
}
}
it's a case by case answer. Return a value when you need one. e.g. addUser() might return a new User object. setUserName() probably doesn't have a return value.
In you case, perhaps return a boolean to indicate whether the value was increased or not?

JUnit - Test Max Number of Objects Created

I have a very small class, BuildThreeObjects, which creates a maximum of 3 Objects using a private int variable, numObjects, to store the count. If the count is < 3, a new Object is returned else null is returned.
Could anyone guide me on how to test if a maximum of 3 Objects are created using JUnit. Looking at the API didn't help much. I assumed assertNotNull or assertNull would be used but I can't think how to.
// Code for BuildThreeObjects class
public class BuildThreeObjects {
private int numObjects = 0;
public Object buildObject() {
if (numObjects<3) {
numObjects++;
return new Object();
}
else return null;
}
}
// Code within the JUnit class; all unnecessary code omitted
private BuildThreeObjects bto;
#Before
public void setUp() throws Exception {
bto = new BuildThreeObjects();
}
#Test
public void testBuild() {
assertNotNull(bto.buildObject());
}
// assertNotNull passes and assertNull fails as it only checks the first object creation
You mean something like this?
class BuildThreeObjects{
int count = 0;
public Object buildObject(){
if(count >= 3){
return null;
} else {
count++;
return new Object();
}
}
}
private BuildThreeObjects bto;
#Before
public void setUp() throws Exception {
bto = new BuildThreeObjects();
}
#Test
public void testBuild() {
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNull(bto.buildObject());
System.out.println(bto.count);
}
// with for loop
for(int i=0; i < 100; i++){
if(i < 3){
assertNotNull(bto.buildObject());
System.out.println(bto.count);
} else {
assertNull(bto.buildObject());
System.out.println(bto.count);
}
}
Just literally do it:
assertNotNull(createObject());
assertNotNull(createObject());
assertNotNull(createObject());
assertNull(createObject());
you could use for-loop also if it could be more expressive.

Passing dynamic primitive type (int) to a method

In Java, the output of s is 0. I do not understand why and would it be possible to somehow get the correct value of s (1000 here)?
public static void main(String args) {
int s = 0;
List<Integer> list = getList(s);
System.out.println("s = " + s);
}
public static List<Integer> getList(int s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s++;
}
}
In C# there were out descriptors to indicate that the variable is going to change if I'm not mistaken..
I'm not going to get the list.size() in general!
In Java, all method arguments are passed by value, i.e. copy. So, changes to the copy are not visible to the caller.
To address your second question, you can just use list.size() on the caller side.
I see two ways
1) Make 's' as static variable and move it to class level
2) Create class with getter/setter for list and int and return the object for getList call
public static MyWrapperObj getList(int s) {
......
return wrapperObj
}
class MyWrapperObj
{
private List<Integer>;
private countS;
....
//getter/setters.
}
Java doesn't allow for passing parameters by reference - but you could wrap it in an object like this:
class IntHolder {
private int s;
IntHolder(int s){
this.s = s;
}
public void setS(int s){
this.s = s;
}
public int getS(){
return s;
}
public void increment(){
s++;
}
}
class Test{
public static void main(String[] args) {
IntHolder s = new IntHolder(0);
List<Integer> list = getList(s);
System.out.println("s = " + s.getS());
}
public static List<Integer> getList(IntHolder s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s.increment();
}
return list;
}
}
In java, arguments passed to methods are passed by value.. you will need to make s a global or instance variable in order to modify it in other methods. This is just the way java works. e.g.
public class Test{
private int s;
public Test(){
s=0;
increment();
//print now will be 1000.
}
private void increment(){
s = 1000;
}
}

Java 'this' keyword

I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}

Categories

Resources