I am getting problem with generating a number based on the given number. Actually I had to get series like DAA001,DAA002,DAA003......DAA999 once DA series is filled with DAA999 it has to generate DAB001...DAB999 and once the series DAB is filled with DAB999 it has to generate DAC001 to DAC999 like that upto DAZ001 toDAZ999.
Here is my code please help me in this.
String start="DA";
String driv[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String PrNumber="";
int count=0;
if(driverprId<=999){
count=0;
start=start+driv[count];
if(driverprId>=1&&driverprId<10){
PrNumber=start+"00"+driverprId;
}
if(driverprId>=10&&driverprId<100){
PrNumber=start+"0"+driverprId;
}
if(driverprId>=100&&driverprId<=999){
PrNumber=start+driverprId;
}
}
if(driverprId>999){
}
return PrNumber;
Something like that should work:
String start="DA";
String driv[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(int i = 0; i < driv.length; i++) {
for(int j = 1; j <= 999; j++) {
String numbers;
if (j / 10 < 1) {
numbers = "00" + j;
} else if (j / 10 < 10) {
numbers = "0" + j;
} else {
numbers = "" + j;
}
PrNumber = start + driv[i] + numbers;
}
Condition only:
if (driverprId / 10 < 1) {
numbers = "00" + j;
} else if (driverprId / 10 < 10) {
numbers = "0" + j;
} else {
numbers = "" + j;
}
Try something like:
int counter = 0;
for (int i=0;i<driv.length;i++) {//for each alphabet
for (int j=0;j<999;j++) { //iterate till 999
start=start+driv[i];//keep using DA A if i is 0 for 999 times
...
if (counter == number) {//number is like number of cells you need
return;
}
counter++;
}
}
Related
I have tried programming recently and there is an exercise online that involves adding the odd integer values of any inputted integer.
My code is able to output the sum of the odd integer values but the exercise asks to output an addition sequence like 1 + 3 + 5... = sum.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number, oddSumPositive = 0, oddSumNegative = 0;
System.out.print("Enter an integer : ");
number = input.nextInt();
oddSumPositive = sumOfOdd_Postive(number);
oddSumNegative = sumOfOdd_Negative(number);
//different scenarios
if(number > 0) {
System.out.println("\nThe Sum of Odd Numbers upto " + number + " = " + oddSumPositive);
}
else if(number < 0) {
System.out.println("\nThe Sum of Odd Numbers upto " + number + " = " + oddSumNegative);
}
else if(number == 0) {
System.out.println("\nThe Sum of Odd Numbers upto 0 = 0");
}
else {
System.out.println("\nError");
}
}
//Method for positive integers
public static int sumOfOdd_Postive(int num)
{
int i, sum = 0;
for(i = 1; i <= num; i++)
{
if (i%2 != 0)
{
sum += i;
System.out.print(i + " ");
}
}
return sum;
}
//Method for negative integers
public static int sumOfOdd_Negative(int num)
{
int i, sum = 0;
for(i = -1; i >= num; i--)
{
if (i%2 != 0)
{
sum += i;
System.out.println((i) + " ");
}
}
return sum;
}
public static int sumOfOddPostive(int num) {
int sum = 0;
for (int i = 1; i <= num; i++) {
if (i%2 != 0) {
sum += i;
if (i != 1) {
System.out.print("+ ");
}
System.out.print(i + " ");
}
}
System.out.println("= " + sum);
// int n = (num + 1)/2; sum = n*n;
return sum;
}
To have a "+" between the terms (one less than the number of terms),
one way is to skip the first (or last term).
It is questionable whether both calculation and output should be so mixed.
Of course the sum can be calculated without all those additions.
I guess you are not printing + as a character anywhere in your code snippet, try below snippet
public static int sumOfOdd_Postive(int num) {
int i, sum = 0;
for(i = 1; i <= num; i++) {
if (i%2 != 0) {
sum += i;
System.out.print(i + "");
if(i != num - 1){ //to avoid + at end of expression
System.out.print("+");
}
}
}
System.out.print("="+sum);
return sum;
}
You want a String so your method should return a String, not an int
Also, you can use StringBuilder in order to create a concatenated String.
Here is a naive implementation :
static String sumOdds(int limit) {
StringBuilder sb = new StringBuilder();
long sum = 0;
for (int i = 1; i <= limit; i++) {
if ( i%2 == 1 ) {
sum += i;
sb.append(i);
if (i + 2 <= limit) {
sb.append(" + ");
} else {
sb.append(" = ").append(sum);
}
}
}
return sb.toString();
}
That being said, as you only want odd or even numbers, there is no point to increment the step one by one and check modulos, you could directly start at 1 and increment steps by 2 :
static String sumOdds(int limit) {
StringBuilder sb = new StringBuilder();
long sum = 0;
for (int i = 1; i <= limit; i+=2) {
sum += i;
sb.append(i);
if (i + 2 <= limit) {
sb.append(" + ");
} else {
sb.append(" = ").append(sum);
}
}
return sb.toString();
}
Also, later, you will discover... Streams !
You can create a Stream of Integer and use some Collectors in order to do fancy things with them.
For example :
static IntStream oddStream(int limit) {
/*
* Here, you can also generate directly odd numbers without filtering
* but it is a bit out of scope.
* See : https://howtodoinjava.com/java8/generate-finite-infinite-stream/
*/
return IntStream.range(1, limit + 1).filter(i -> i % 2 == 1);
}
Then, you can use it to get all the values, map them to a String and collect them in a String, where the values are separated with " + "
String str = Main.oddStream(limit)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" + "));
Also, you can use the same Stream in order to sum all the values :
long sum = Main.oddStream(limit).sum();
Which allows you to create the desired result like this :
static String sumEven(int limit) {
String str = Main.oddStream(limit)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" + "));
long sum = Main.oddStream(limit).sum();
return str + " = " + sum;
}
I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}
The problem is to display the first 50 prime numbers in 5 lines, each of which contains 10 numbers. I've created a program to output the first 50 prime numbers but I don't know how to split them so they output 10 numbers per line. I am a beginner level programmer and I really need help on this.
public class Lab4 {
public static void main(String[] args) {
int i = 0;
int num = 0;
String primeNumbers = " ";
for (i = 1; i <= 230; i++)
{
int counter = 0;
for (num = i; num >= 1; num--)
{
if (i % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println(primeNumbers);
}
}
You need to count how many items you already added and once you have 10 you need to put new line. Also I changed String to StringBuilder because concatenating in a loop is not very good, you can read about it here StringBuilder vs String concatenation
int i = 0;
int num = 0;
int lineCounter = 0;
StringBuilder primeNumbers = new StringBuilder();
for (i = 1; i <= 230; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers.append(i).append(" ");
lineCounter++;
}
if (lineCounter == 10) {
primeNumbers.append(System.lineSeparator());
lineCounter = 0;
}
}
System.out.println(primeNumbers);
Just add this piece of code below after this line in your code: primeNumbers = primeNumbers + i + " ";
if (newLineCount == 10) {
primeNumbers += '\n';
newLineCount = 0;
}
newLineCount++;
Also init newLineCount before the loop: int newLineCount = 0;
Additionally, as mentioned in the comments, consider using StringBuilder instead of String, or even better ArrayList to store your numbers, then you can have method to print values from your ArrayList in whatever formatted way you want (with tabs, alignment, new lines...)
Here is the code that suits your needs. I haven't changed anything in your code, just added mine to suit your needs.
public class print_prime_numbers_10_per_line {
public static void main(String[] args) {
int i = 0;
int num = 0;
String primeNumbers = "";
for (i = 1; i <= 230; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i + " ";
}
}
String[] integerStrings = primeNumbers.split(" ");
int[] integers = new int[integerStrings.length];
for (int x = 0; x < integers.length; x++) {
integers[x] = Integer.valueOf(integerStrings[x]);
}
for (int g = 0; g < integers.length; g++) {
if (g % 11 == 0) {
System.out.println();
} else {
System.out.print(integers[g] + " ");
}
}
}
}
Note: no mapping, no sorting
Here's my code:
public static void countArray(int[] n){
int[] m = new int[n.length]; //50 elements of integers between values of 10 & 20
int count = 0;
int sum = 0;
for ( int i = 0; i < n.length ; i++){
m[i] = n[i]; //make a copy of array 'n'
System.out.print(m[i]+" ");
}System.out.println();
for ( int j =0; j < n.length ; j++){
count =0;
for(int i = 0; i < n.length ; i++){
if (n[j]%m[i]==0 && n[j] == m[i])
count++;
}if ( n[j]%m[j] == 0)
System.out.println(m[j] + " occurs = " + count);
}
}
So the problem is: I get repeating results like : "25 occurs = 5", on different lines.
What I think: the problem occurs because of if ( n[j]%m[j] == 0)
so I tried if ( n[j]%m[j+1] == 0). Another problem occurs since m[j] will be m[50] so it crashes but sort of give me the results that I want.
Result that I want: something like this: no repetitions and covers all the random integers on a set
17 occurs = 3
23 occurs = 2
19 occurs = 3
15 occurs = 2
12 occurs = 2
With some adaptation your code should work :
public static void countArray(int[] n){
boolean [] alreadyCounted = new boolean[n.length];
for (int i = 0; i < n.length ; i++){
int count = 0;
if (alreadyCounted[i]) {
// skip this one, already counted
continue;
}
for(int j = 0; j < n.length ; j++){
if (n[i] == n[j]) {
// mark as already counted
alreadyCounted[j] = true;
count++;
}
}
System.out.println(n[i] + " occurs = " + count);
}
}
You could definitely use the same logic with better code, I just tried to follow the original "coding style";
This is O(n^2) solution (read "very slow").
If you could use sorting, you could do it in O(n log(n)) - that is fast.
With mapping you could do it in O(n) - that is blazingly fast;
If you exploit the input limit you can lose the nested loop:
public static void main(String[] args)
{
//6 elements of integers between values of 10 & 20
int[] countMe = { 10, 10, 20, 10, 20, 15 };
countArray(countMe);
}
/** Count integers between values of 10 & 20 (inclusive) */
public static void countArray(int[] input)
{
final int LOWEST = 10;
final int HIGHEST = 20;
//Will allow indexes from 0 to 20 but only using 10 to 20
int[] count = new int[HIGHEST + 1];
for(int i = 0; i < input.length; i++)
{
//Complain properly if given bad input
if (input[i] < LOWEST || HIGHEST < input[i])
{
throw new IllegalArgumentException("All integers must be between " +
LOWEST + " and " + HIGHEST + ", inclusive");
}
//count
int numberFound = input[i];
count[numberFound] += 1;
}
for(int i = LOWEST; i <= HIGHEST; i++)
{
if (count[i] != 0)
{
System.out.println(i + " occurs = " + count[i]);
}
}
}
try this :(sort the array and then count the occurence of element)
public static void countArray(int[] n) {
int count = 0;
int i, j, t;
for (i = 0; i < n.length - 1; i++) // sort the array
{
for (j = i + 1; j < n.length; j++) {
if (n[i] > n[j]) {
t = n[i];
n[i] = n[j];
n[j] = t;
}
}
}
for (i = 0; i < n.length;)
{
for (j = i; j < n.length; j++) {
if (n[i] == n[j])
{
count++;
} else
break;
}
System.out.println(n[i] + " occurs " + count);
count = 0;
i = j;
}
}
Here's a nice, efficient way to do it, rather more efficiently than the other solutions posted here. This one runs in O(n) time, where the array is of length n. It assumes that you have some number MAX_VAL, representing the maximum value that you might find in your array, and that the minimum is 0. In your commenting you suggest that MAX_VAL==20.
public static void countOccurrences(int[] arr) {
int[] counts = new int[MAX_VAL+1];
//first we work out the count for each one
for (int i: arr)
counts[i]++;
//now we print the results
for (int i: arr)
if (counts[i]>0) {
System.out.println(i+" occurs "+counts[i]+" times");
//now set this count to zero so we won't get duplicates
counts[i]=0;
}
}
It first loops through the array increasing the relevant counter each time it finds an element. Then it goes back through, and prints out the count for each one. But, crucially, each time it prints the count for an integer, it resets that one's count to 0, so that it won't get printed again.
If you don't like the for (int i: arr) style, this is exactly equivalent:
public static void countOccurrences(int[] arr) {
int[] counts = new int[MAX_VAL+1];
//first we work out the count for each one
for (int i=0; i<arr.length; i++)
counts[arr[i]]++;
//now we print the results
for (int i=0; i<arr.length; i++)
if (counts[arr[i]]>0) {
System.out.println(arr[i]+" occurs "+counts[arr[i]]+" times");
//now set this count to zero so we won't get duplicates
counts[arr[i]]=0;
}
}
I am trying to print the sequence of numbers 11223344556677889900 using nested for loops. I am unsure of the algorithm to print the sequence since it ends in 00. I have the following method code but I print the 00 as literals and am sure that there must be a better way. Any help is much appreciated.
public static void drawNumbers(){
for (int line = 1; line <= 2; line++) {
for (int i =1; i <= 9; i++) {
for (int j =1; j<=2; j++) {
System.out.print(i);
}
}
System.out.print("00");
}
}
Run your loop up to 10 and instead of:
System.out.print(i);
do:
System.out.print(i % 10);
public static void drawNumbers(){
for (int line = 1; line <= 2; line++){
for (int i =1; i <= 10; i++){
for (int j =1; j<=2; j++){
System.out.print(i%10);
}
}
}
}
You can run the "i" loop until 10 and print i%10. This would print 0 when the value reaches 10.
One other way would be to insert an if statement inside the for where you would check if the value of i was equal to "10", and if it were, it would print the value "00"
Just only print the last digit of i
for (int i = 1; i <= 10; i++) {
String s = String.valueOf(i);
int lastDigit = s.length() - 1; // last digit position in string
System.out.print(s.substring(lastDigit, lastDigit + 1)); // print last digit
System.out.print(s.substring(lastDigit, lastDigit + 1)); // print last digit
}
Output:
11223344556677889900
Changed the logic a little to fit your requirement
public static void drawNumbers() {
for (int line = 1; line <= 1; line++) {
for (int i =1; i <= 10; i++) {
for (int j =1; j<=2; j++) {
if(i==10) {
System.out.print(0);
} else {
System.out.print(i);
}
}
}
}
}
To use only one loop run it like
public static void drawNumbers() {
for(int i = 1 ;i <= 10; i++) {
if(i ==10) {
System.out.print(0 + "" + 0);
} else {
System.out.print(i + "" + i);
}
}
}