cows and bulls methods - java

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;
}

Related

what is the maximum possible number of monsters you can defeat?

Problem Statement:
While playing an RPG game, you were assigned to complete one of the hardest quests in this game. There are n monsters you'll need to defeat in this quest. Each monster i is described with two integer numbers - poweri and bonusi. To defeat this monster, you'll need at least poweri experience points. If you try fighting this monster without having enough experience points, you lose immediately.
You will also gain bonusi experience points if you defeat this monster. You can defeat monsters in any order. The quest turned out to be very hard - you try to defeat the monsters but keep losing repeatedly. Your friend told you that this quest is impossible to complete. Knowing that, you're interested, what is the maximum possible number of monsters you can defeat?
Input:
The first line contains an integer, n, denoting the number of monsters.
The next line contains an integer, e, denoting your initial experience.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, poweri, which
represents power of the corresponding monster.
Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, bonusi, which represents bonus for defeating the corresponding monster.
Sample cases:
Input 2 123 78 130 10 0
Output 2
Output description
Initial experience level is 123 points.
Defeat the first monster having power of 78 and bonus of 10. Experience level is now 123+10=133.
Defeat the second monster.
What I have tried:
public static int defeat(int [] monster,int bonus[],int n,int exp){
if(n==0)
return 0;
if(n==1 && monster[0]<=exp)return 1;
if(n==1 && monster[0]>exp) return 0;
if(monster[n-1]<=exp){
return defeat(monster,bonus,n-1,bonus[n-1]+exp )+ defeat(monster,bonus,n-1,exp);
}else{
return defeat(monster,bonus,n-1,exp);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int exp = s.nextInt();
int monst[] = new int[n];
int bonus[] = new int[n];
for (int i = 0; i < n; i++) {
monst[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
bonus[i] = s.nextInt();
}
System.out.println(defeat(monst,bonus,n,exp));
}
I am not getting correct answers with this solution.
I thought of this problem as 0/1 knapsack problem( correct me If I am wrong). Also can you provide me DP solution of this problem.
You can just sort the monsters from lowest to highest power required and defeat them in that order.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int exp = s.nextInt();
int monst[] = new int[n];
int bonus[] = new int[n];
for (int i = 0; i < n; i++) {
monst[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
bonus[i] = s.nextInt();
}
class Monster {
private final int power, bonus;
public Monster(int power, int bonus){
this.power = power;
this.bonus = bonus;
}
}
Monster[] monsters = new Monster[n];
for(int i = 0; i < n; i++) monsters[i] = new Monster(monst[i], bonus[i]);
Arrays.sort(monsters, Comparator.comparingInt(m -> m.power));
int count = 0;
for(Monster m: monsters){
if(exp < m.power) break;
exp += m.bonus;
++count;
}
System.out.println(count);
}
Perhaps I am too simplistic, but I would try it as below:
First create a class Monster like this:
public class Monster
{
final int m_Power;
final int m_Bonus;
public Monster( final int power, final int bonus )
{
m_Power = power;
m_Bonus = bonus;
}
public final int getPower() { return m_Power; }
public final int getBonus() { return m_Bonus; }
}
Next, initialise a list of Monsters like this:
public static void main( String... args )
{
final var scanner = new Scanner( System.in );
final var n = scanner.nextInt();
final var experience = scanner.nextInt();
final var power [] = new int [n];
for( var i = 0; i < n; ++i )
{
power [i] = scanner.nextInt();
}
List<Monster> monsters = new ArrayList<>( n );
for( var i = 0; i < n; ++i )
{
monsters.add( new Monster( power [i], scanner.nextInt();
}
monsters.sort( (m1,m2) ->
{
final var p = m1.getPower() - m2.getPower();
return p == 0 ? m2.getBonus() - m1.getBonus(() : p;
} ); //*1
System.out.println( defeat( monsters, experience ) );
}
*1 -> this implementation of the comparator works well only for power and bonus values that are small compared to MAX_INT.
The list monsters now contains the monsters sorted by their power in ascending order; monsters with the same power are ordered by their bonus values in descending order.
Now my implementation of defeat() would look like this:
public final int defeat( final List<Monster> m, final int initialExperience )
{
var experience = initialExperience;
var retValue = 0;
final Stack<Monster> monsters = new LinkedList<>( m );
while( !monsters.empty() )
{
var monster = monsters.pop();
if( experience > monster.getPower() )
{
experience += monster.getBonus();
++retValue;
}
else break;
}
return retValue;
}
n=int(input())
e=int(input())
P=[]
for i in range(n):
P.append(int(input()))
B=[]
for i in range(n):
B.append(int(input()))
c=0
f=True
while n>0 and f:
f=False
i=0
while i<n:
if e>=P[i]:
e+=B[i]
P.pop(i)
B.pop(i)
n-=1
c+=1
f=True
i-=1
i+=1
print(c)
import java.io.*;
import java.util.*;
class Player {
int exp;
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
}
class Monster {
int power;
int bonus;
public int getPower() {
return this.power;
}
public int getBonus() {
return this.bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
public void setPower(int power) {
this.power = power;
}
}
class Calc {
public int calc() {
Scanner sc = new Scanner(System.in);
//number of monsters
System.out.println("enter the number of monsters");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("enter the power of the player");
Player player = new Player();
player.setExp(sc.nextInt());
//declaration of array type object of monster
Monster monster[] = new Monster[n];
//value setting completed
for (int i = 0; i < n; i++) {
//allocation of object to the real
monster[i] = new Monster();
System.out.println("enter the power of monster");
monster[i].setPower(sc.nextInt());
System.out.println("enter the bonus that to be earned after killing the monster");
monster[i].setBonus(sc.nextInt());
}
//calculate win or loose
int count = 0;
int flag = 0;
//**
for (int i = 0; i < n; i++) {
if (player.getExp() >= monster[i].getPower()) {
player.setExp(player.getExp() + monster[i].getBonus());
count = count + 1;
// flag = flag + 1;
} else if (player.getExp() < monster[i].getPower()) {
for (int j = 0; j < n; j++)
arr[j] = i;
//count = count;
flag = flag + 1;
}
//**
for (int t = 0; t < flag; t++) {
if (player.getExp() >= monster[arr[t]].getPower()) {
count = count + 1;
}
}
}
return count;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println("welcome to the loosing game");
Calc c = new Calc();
System.out.println("no of monster killed" + c.calc());
}
}
#include<bits/stdc++.h>
using namespace std;
struct Monsters
{
int power;
int bonus;
};
class Solution
{
public:
//Function to find the maximum number of activities that can
//be performed by a single person.
static bool compare(Monsters a, Monsters b)
{
if(a.power < b.power) return 1;
else if(a.power > b.power) return 0;
else return 1;
}
int MonstersKill(vector<int> power, vector<int> bonus, int n, int exp)
{
Monsters arr[n];
for(int i = 0; i < n; i++)
{
arr[i].power = power[i];
arr[i].bonus = bonus[i];
}
sort(arr, arr+n, compare);
int count = 0;
for(int i = 0; i < n; i++)
{
if(arr[i].power <= exp)
{
count++;
exp += arr[i].bonus;
}
else
break;
}
return count;
}
};
int main()
{
int n, exp;
cin >> n >> exp;
vector<int> power(n), bonus(n);
//adding elements to arrays power and bonus
for(int i=0;i<n;i++)
cin>>power[i];
for(int i=0;i<n;i++)
cin>>bonus[i];
Solution ob;
cout << ob.MonstersKill(power, bonus, n, exp) << endl;
return 0;
}
Time Complexity : O(N * Log(N))
Auxilliary Space: O(N)

Loading space-separated user input to array

I'm new to Java. I've spent hours trying to figure out why this code doesn't work. It's supposed to take user input integers separated by whitespace, and load them into an int array. Then, the numbers are supposed to be sorted in descending order, and the frequency of repeated inputs has to be displayed in a separate int array.
I'm getting zeroes in the output though. Can anyone help me fix this program?
This is what I have:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] inputNumbers = new int[50];
int[] ocurrences = new int[50];
int size = 0;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
System.out.println("Enter eaach of the numbers. Please put a space between each number.");
String arrayString = input.next();
input = new Scanner(arrayString);
while(input.hasNextInt())
{
int nextNumber = input.nextInt();
if(!isInArray(inputNumbers, size, nextNumber))
{
inputNumbers[size] = nextNumber;
ocurrences[size] = 1;
size++;
}
else
{
int index = search(inputNumbers, size, nextNumber);
ocurrences[index]++;
}
}
sort(inputNumbers, ocurrences, size);
System.out.println("N\t\tCount");
for(int i = 0; i < size; i++)
{
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
}
public static void sort(int[] inputNumbers, int[] ocurrences, int size)
{
for(int current = 0; current < size; current++)
{
int max = current;
for(int i = current; i < size; i++)
{
if(inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return true;
}
return false;
}
}
The current output is:
How many numbers to enter? (At most 50)
4
Enter eaach of the numbers. Please put a space between each number.
5 5 4 7 8
N Count
5 1
0 0
0 0
0 0
0 0
BUILD SUCCESSFUL (total time: 11 seconds)
It should have been something like
N Count
8 1
7 1
5 2
4 1
Initialize the array where we know the exact size, so it avoid unnecessary memory utilization.
Also input.next() will read only the next complete token not the entire line. That was the mistake in the code.
Finally the scanner resource was not closed.
I have refactored your code, please check it.
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int[] inputNumbers, ocurrences;
int index = 0, size;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
inputNumbers = new int[size];
ocurrences = new int[size];
System.out.println("Enter each of the numbers. Please put a space between each number.");
for (int i = 0; i < size; i++) {
int nextNumber = input.nextInt();
if (!isInArray(inputNumbers, nextNumber)) {
inputNumbers[index] = nextNumber;
ocurrences[index] = 1;
index++;
} else {
int oIndex = search(inputNumbers, nextNumber);
ocurrences[oIndex] ++;
}
}
sort(inputNumbers, ocurrences);
System.out.println("N\t\tCount");
for (int i = 0; i < index; i++) {
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
} finally {
input.close();
}
}
public static void sort(int[] inputNumbers, int[] ocurrences) {
int size = inputNumbers.length;
for (int current = 0; current < size; current++) {
int max = current;
for (int i = current; i < size; i++) {
if (inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return true;
}
return false;
}

code to find longest substring with unique K characters not working for all inputs

Given a String, ""aabbcdeeeeggi" and k=3, the code should find longest substring with maximum of k unique characters. For the above input, it should be "deeeeggi".
Here is an elegant O(n) solution for the problem in Python. I am implementing in Java. but I am not getting the desired output for all the inputs.
public class SubStringWithKUniqueCharacters {
public static void main(String[] args){
System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 3));
System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 2));
}
public static String longestSubStringWithUniqueK(String input, int k){
int len = input.length();
Set<Character> unique = new HashSet<>();
int i = 0;
int j = 0;
int count = 0;
int maxStartIndex = 0;
int maxEndIndex = 0;
int maxLen = 0;
char[] inputArr = input.toCharArray();
while (i<len){
if (count==k && j -i > maxLen){
maxStartIndex = i;
maxEndIndex = j;
maxLen = maxEndIndex - maxStartIndex;
}
if (count<k && j<len){
if (unique.add(inputArr[j])){
count++;
}
j++;
}
else {
if (unique.remove(inputArr[i])){
count--;
}
i++;
}
}
return input.substring(maxStartIndex,maxEndIndex);
}
}
Here is the output:
eeeeggi //correct output
eeeggi //incorrect output
I am not able to capture where the bug is. Any help would be much appreciated.
Thanks
Your implementation does not work the way as expected, is because the original python solution has bug. I made some modifications to your code. Hope it's now all right:
public class SubStringWithKUniqueCharacters {
public static void main(String[] args){
System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 3));
System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 2));
}
public static String longestSubStringWithUniqueK(String input, int k){
int len = input.length();
Set<Character> unique = new HashSet<>();
int i = 0;
int j = 0;
int count = 0;
int maxStartIndex = 0;
int maxEndIndex = 0;
int maxLen = 0;
char[] inputArr = input.toCharArray();
while (i<len){
if (count==k && j -i > maxLen){
maxStartIndex = i;
maxEndIndex = j;
maxLen = maxEndIndex - maxStartIndex;
}
// 1. if we reach the end of the string, we're done.
if (j + 1 > len){
break;
}
// 2. changed to count <= k here
else if (count<= k && j<len){
if (unique.add(inputArr[j])){
count++;
}
j++;
}
else {
if (unique.remove(inputArr[i])){
// 3. remove all consecutive chars of the same value
char c = inputArr[i]; // save as temp char
while (inputArr[i] == c)
{
i++;
}
count--;
}
}
}
return input.substring(maxStartIndex,maxEndIndex);
}
}
The output now is:
deeeegg
eeeegg

Find smallest number K , if exists, such that product of its digits is N. Eg:when N = 6, smallest number is k=16(1*6=6) and not k=23(2*3=6)

I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);

4 Digit Java Counter

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]);
}
}
}

Categories

Resources