4 Digit Java Counter - java

Hello I am coding something and I need a four digit counter, that when the method is called increases by one each time until I hit 9999. For example, before I call the method, the counter's value will be 0000. After I call the method it will increase to 0001, then 0002, and so on.
I will also like to be able to individually call each digit. I have no idea how this could be done, if someone can help me that'd be great.
What I tried doing:
private int[] count = new int[4];
private int counter;
private void countUp() {
count[counter++];
if (counter > count.length -1) {
counter = 0;
}
}

Try this simple solution:
private int[] count = new int[4];
private int counter;
private void countUp() {
counter++;
count[0] = counter %10;
count[1] = counter /10 % 10;
count[2] = counter /100 % 10;
count[3] = counter /1000 % 10;
}

Ngygens wont have a single digit per array. This has a single digit per array bit
private int[] count = new int[4];
private int counter;
private void countUp() {
counter++;
count[3] = counter /1000;
count[2] = (counter /100) % 10;
count[1] = (counter /10) % 10;
count[0] = counter %10;
}

If you want a solution that doesn't need heavy computation every time you increment. Furthermore it is fully scalable if you want a different maximum than 9999.
private int counter;
private int max = 9999;
private void countUp() {
if (counter < max)
counter++;
}
private int getDigit(int n) {
String counterAsString = String.valueOf(counter);
if (n < counterAsString.length())
return Integer.parseInt(String.valueOf(counterAsString.charAt(n)));
return 0;
}

I would go with an object-oriented approach. This would allow you to access methods to easily increment digits, peek at a particular digit, etc. While meter is an integer, the bind variable will keep the meter to four digits.
public class Counter {
private int meter = 0;
private boolean bind = true;
public static final int DIGIT_1 = 1000;
public static final int DIGIT_2 = 100;
public static final int DIGIT_3 = 10;
public static final int DIGIT_4 = 1;
/*
* Look at a particular digit's value
*/
public int peek(int digit) {
return (meter / digit) % 10;
}
/*
* By default, increments by 1.
*/
public void increment() {
this.increment(Counter.DIGIT_4);
}
/*
* Increments one of the digits
*/
public void increment(int digit) {
if(digit != Counter.DIGIT_1
&& digit != Counter.DIGIT_2
&& digit != Counter.DIGIT_3
&& digit != Counter.DIGIT_4) {
return;
}
this.meter += digit;
if(bind) {
this.meter = Math.abs(this.meter % 10000);
}
}
/*
* By default, adds the number to the right-most digit.
*/
public void add(int number) {
this.add(number, Counter.DIGIT_4);
}
public void add(int number, int digit) {
if(digit != Counter.DIGIT_1
&& digit != Counter.DIGIT_2
&& digit != Counter.DIGIT_3
&& digit != Counter.DIGIT_4) {
return;
}
this.meter += (digit * number);
if(bind) {
this.meter = Math.abs(this.meter % 10000);
}
}
/*
* Prints out the counter as four numbers
*/
#Override
public String toString() {
return String.format("%04d", this.meter);
}
/*
* An example
*/
public static void main(String[] arg) {
Counter c = new Counter();
c.add(-15000);
c.increment(Counter.DIGIT_2);
System.out.println(c + ": " + c.peek(Counter.DIGIT_4));
}
}

You don't need array:
private String count = "0000";
private int counter;
private void countUp() {
if (9999 < counter) {
return;
}
counter ++;
count = String.format("%04d", counter);
}

Try this:
Integer numwithoutzero;
char[] things = new char[4];
int zerocount = 4;
private void countUp() {
char[]c = String.valueOf(numwithoutzero).toCharArray();
for(int i = 0;i<=zerocount;i++)things[i]='0';
for(int i = 0;i<=String.valueOf(numwithoutzero).length();i++){
for(int b = c.length;b>=0;b--){
things[b] = c[i];
}
}
numwithoutzero++;
zerocount = 4 - c.length
}

didn't get you well but if you want a sequence of 0000,0001,0002,0003,...9999 just try this:
String[] counter=new String[10000];
for (int i=0;i<=9999;i++){
counter[i]=String.format("%04d", i);
}

import java.util.Scanner;
public class count0001to0002{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
int num = sc.nextInt();
int[] count = new int[4];
for(int x=0; x<=num; x++){
int counter = x;
count[3] = counter %10;
count[2] = counter /10 % 10;
count[1] = counter /100 % 10;
count[0] = counter /1000 % 10;
for(int y=0; y<4; y++){
System.out.print(count[y]);
}
System.out.println();
}
for(int x=0; x<4; x++){
System.out.print(count[x]);
}
}
}

Related

How to count happy numbers

As an assignment I need to count the amount of happy numbers* in a given range. I did most of that already:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String inputLowerRange = scan.nextLine().trim();
String inputUpperRange = scan.nextLine().trim();
int lowerRange = Integer.parseInt(inputLowerRange);
int upperRange = Integer.parseInt(inputUpperRange);
Set<Integer> numbers = new HashSet<Integer>();
for (int i = lowerRange; i <= upperRange; i++)
while(lowerRange>0) {
upperRange += (lowerRange % 10)*(lowerRange % 10);
lowerRange /=10;
}
int counter = 0;
for (int i = lowerRange; i <= upperRange; i++) {
}
System.out.println(counter);
}
}
Now the code just needs to count the happy numbers* present within that range. I understand it is best done with:
if ............... counter++
but how exactly would I need to do it?
*A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. 13 is a happy number because 1^2 + 3^2 = 10
And 1^2 + 0^2 = 1, thus 13 is a happy number.
int counter = 0;
for(int i=lowerRange;i<=upperRange;i++)
{
int num=i,sum=0,rem;
while(sum!=1 && sum!=4)
{
sum=0;
while(num!=0)
{
rem=num%10;
sum+=(rem*rem);
num/=10;
}
num=sum;
}
if(sum==1)
counter++
}
System.out.println(counter);
the issue with your code is you are making direct changes to lowerRange and upperRange which will result in not iterating properly. You need to use temp variables for those. Also you forgot this condition while(sum!=1 && sum!=4){}
Set<Integer> numbers = new HashSet<Integer>(); //what's this for?
for (int i = lowerRange; i <= upperRange; i++)
while(lowerRange>0) { // missed one outer while loop
upperRange += (lowerRange % 10)*(lowerRange % 10); // changes to upperRange
lowerRange /=10; // changes to lowerRange
}
Try this.
static boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (n > 1 && !set.contains(n)) {
set.add(n);
n = String.valueOf(n).chars()
.map(c -> c - '0')
.reduce(0, (sum, i) -> sum + i * i);
}
return n == 1;
}
public static void main(String args[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println(IntStream.rangeClosed(scan.nextInt(), scan.nextInt())
.filter(i -> isHappy(i))
.count());
}
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
System.out.println(isHappy(null, 11));
}
public static boolean isHappy(Set<Integer> previousNumbers, int number) {
if (previousNumbers == null) previousNumbers = new HashSet<>();
else if (previousNumbers.contains(number)) return false;
if (number == 4) return true;
int length = getNumberLength(number);
int subNumber = 0;
for (int i = 0; i < length; i++) {
int digit = getNumberDigit(number, i);
subNumber += digit * digit;
}
previousNumbers.add(number);
return isHappy(previousNumbers, subNumber);
}
public static int getNumberDigit(int number, int index) {
int pow = (int) Math.pow(10, index);
return (number % (pow * 10)) / pow;
}
public static int getNumberLength(int number) {
int length = 0;
for (long temp = 1; temp <= number; temp *= 10)
length++;
return length;
}
}

Why does the below code returns wrong answer?

Here I'm comparing ArmstrongNo & out were both have same values(371), but is printing the wrong statement.
public class ArmstrongNumber {
static int ArmstrongNo = 371;
static int sum = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
ArmstrongNumber am = new ArmstrongNumber();
int out = am.Armstrong();
System.out.println(out);
if (ArmstrongNo == out)
System.out.println("It is an Armstrong number");
else
System.out.println("Not an Armstrong number");
}
public int Armstrong() {
int length = String.valueOf(ArmstrongNo).length();// To find the length of integer
for (int x = 0; x < length; x++) {
int i = ArmstrongNo % 10;
int cube = i * i * i;
sum += cube;
ArmstrongNo = ArmstrongNo / 10;
}
return sum;
}
}
OUTPUT:
371
Not an Armstrong number
you are overwriting your ArmstrongNo here ArmstrongNo = ArmstrongNo / 10;
sum is then 371 but ArmstrongNo is 0
EDIT
this fixes your code (at least functionally)
public int Armstrong() {
int ArmstrongNoCopy = ArmstrongNo;
int length = String.valueOf(ArmstrongNoCopy)
.length();// To find the length of integer
for (int x = 0; x < length; x++) {
int i = ArmstrongNoCopy % 10;
int cube = i * i * i;
sum += cube;
ArmstrongNoCopy = ArmstrongNoCopy / 10;
}
return sum;
}
Your method public int Armstrong() modifies static variable ArmstrongNo. To avoid this, do declare this static variable as final and add local variable to the method public int Armstrong():
final static int ArmstrongNo = 371;
public int Armstrong() {
int ArmstrongNo = ArmstrongNumber.ArmstrongNo;
//...
}

Finding the median and max value of an array in java

I used this code to calculate the max value and the median element in an array of integers, but when I call the methods in my client class, both of these two methods produce an output of zero. The name of the array is "grades" and it is made of randomly generated integers
import java.util.*;
public class StudentGrades {
private int [] grades;
//Constructor
public StudentGrades ( int students)
{
Random number = new Random();
grades = new int[students];
for (int i = 0 ; i < students ; i++)
{
grades[i] = number.nextInt(99) + 1;
}
}
double median;
public void median()
{
Arrays.sort(grades) ;
double median ;
if (grades.length % 2 == 0)
{
int indexA = (grades.length - 1 ) /2;
int indexB = (grades.length)/2;
median = ((double) (grades[indexA] + grades[indexB]))/2;
}
else
{
int medIndex = (grades.length-1) / 2;
median = grades[ medIndex ];
}
}
public double getMedian()
{
return median;
}
int max;
public int getHighest()
{
for(int i = 0 ; i < grades.length - 1 ; i++)
{
int max = 0;
if(grades[i] > max)
{
max = grades[i];
}
}
return max;
}
In my driver, I simply had to prove that the method worked correctly, so it's:
System.out.println(" The highest grade is" + grades.getHighest());
System.out.println("The median grade is" + grades.getMedian());
Few mistakes.
1.) Might be calling getMedian(), whereas the logic is inside median() method.
2.) Inside method, getHighest(),
a.) No need to loop the array, since array is already sorted. So i have commented the code.
Just get the value at last index of array.
public class Test {
static int max;
static double median;
static int[] grades = { 2, 3, 4, 5, 62, 34 };
public static void main(String args[]) {
Arrays.sort(grades);
median();
getHighest();
System.out.println(median);
System.out.println(max);
}
public static void median() {
if (grades.length % 2 == 0) {
int indexA = (grades.length - 1) / 2;
int indexB = (grades.length) / 2;
median = ((double) (grades[indexA] + grades[indexB])) / 2;
} else {
int medIndex = (grades.length - 1) / 2;
median = grades[medIndex];
}
}
public double getMedian() {
return median;
}
public static int getHighest() {
/* for (int i = 0 ; i < grades.length ; i++) {
if (grades[i] > max) {
max = grades[i];
}
}*/
max = grades[grades.length - 1];
return max;
}
Output
4.5
62

cows and bulls methods

I'm not sure if anyone is familiar with the game cows and bulls. Basically I'm trying to write a method that is a user enters in a number of 1234 and another user enters in 4305 this will give them 2 cows because the numbers are in the first number but in the wrong index. If they are in the same index then they get a bull. I must call methods that I have previously coded. I have it to where it counts the number of correct numbers found in the first number given but I can't figure out how to get it to NOT count them if they are in the same index. Any advice would be great.
public static int numDigits(int number)
{
int counter = 0;
while(number !=0)
{
int digit = number % 10;
number= number /10;
counter++;
}
return counter;
}
public static int getDigit(int number, int i)
{
int negative =-1;
int counter = 0;
int digit = 0;
if(i>numDigits(number)|| i == 0)
{
return negative;
}
while(counter < i)
{
digit = number % 10;
number = number / 10;
counter++;
}
return digit;
}
public static int indexOf (int number, int digit)
{
int counter = 0;
int negative = -1;
for(int i = 0; i<=numDigits(number); i++)
{
counter++;
if(getDigit(number,i)== digit)
{
return counter-1;
}
}
return negative;
}
public static int getCows(int first, int second)
{
int counter = 0;
for(int i = 0; i<numDigits(first); i++)
{
if(getDigit(first,i)==getDigit(second,i))
{
counter++;
}
}
return counter;
}
Threw this together for fun (running in groovy console, possibly not perfectly valid java).
public static int[] getCowsBulls(int match, int guess)
{
Character[] matchChars = Integer.toString(match).getChars();
Character[] guessChars = Integer.toString(guess).getChars();
int minLen = Math.min(matchChars.length, guessChars.length);
Set<Character> matchSet = new HashSet<>();
matchSet.addAll(matchChars);
int cows = 0;
int bulls = 0;
for(int i = 0; i < minLen; i++) {
Character gc = guessChars[i];
boolean inMatch = matchSet.contains(gc);
if(!inMatch) { continue; }
if(matchChars[i].equals(gc)) {
bulls++;
} else {
cows++;
}
}
return new Integer[]{ cows, bulls };
}
You are asking how to not count the bulls as cows?
public static int getCows(int first, int second)
{
int counter = 0;
for(int i = 0; i<numDigits(first); i++)
{
for(int j = 0; i<numDigits(second); j++)
{
if(j!=i && getDigit(first,i)==getDigit(second,j) )
{
counter++;
}
}
}
return counter;
}

Fibonacci sequence in Java using for statements

I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}

Categories

Resources