This question already has answers here:
How to format numbers to same number of digits, 0-padded?
(3 answers)
Closed 9 years ago.
I must display all server names in the range of v10000 up to v10500.
Below is the code that I tried, but sometimes it displays a zero.
String template = "v10";
int count = 0;
while (count < 501) {
String number;
if (count < 100) {
number = "00" + Integer.toString(count);
} else if(count < 10) {
number = "0" + Integer.toString(count);
} else {
number = Integer.toString(count);
}
String server = template + number;
System.out.println(server);
count++;
}
But when I show this solution to my boss, he just laughs and says:
I can do this better.
How can I alter my code to make it work properly? I'm new to Java.
I would do
for(int i = 10000; i <= 10500; i++)
System.out.println("v" + i);
It is a very long way. Better use String.format()
A working solution for you would be:
for (int i = 0; i <= 500; i++) {
String server = String.format("v10%03d", i);
System.out.println(server);
}
The format String is builded like that:
v10 -> your String template of the server
%0 --> the zeros you need
3d --> three digits will be added
So your int i will be formatted like that.
Every other answers suggest a better approach to this problem. I was going myself to suggest to use format, but a loop starting from 10000 is fine too:
for (int i = 0; i <= 500; i++) {
String server = String.format("v10%03d", i);
System.out.println(server);
}
or simply (and faster):
for(int i = 10000; i <= 10500; i++) {
System.out.println("v" + i);
}
But I think that we should also fix the bug in OP's code:
while (count < 501){
String number;
if(count < 100){
number = "00" + Integer.toString(count);
}else if(count < 10){
number = "0" + Integer.toString(count);
}else{
number = Integer.toString(count);
}
String server = template + number;
System.out.println(server);
count++;
}
I would recommend using a for-loop instead but that's not the problem. The problem is the order of the tests. if count < 100 is false, then count < 10 is also false. You will never enter this block. Switch the order of your if statements.
So the fixed code:
for (int count = 0; count <= 500; count++){
String number;
if(count < 10){
number = "00" + Integer.toString(count);
}else if(count < 100){
number = "0" + Integer.toString(count);
}else{
number = Integer.toString(count);
}
String server = template + number;
System.out.println(server);
}
Just use a for loop:
for(int i = 10000; i <= 10500; i++)
System.out.println("v" + i);
String template = "v";
for(int i=10000;i<=10500;i++){
System.out.println(template+i);
}
Use String.format inside a for loop:
for (int i = 10000; i <= 10500; ++i) {
System.out.println(String.format("v%d", i));
}
This will count through those integers and prepend a "v" to each.
You can do a for from 10000 to 10500 and convert that int (or whichever numeric type you use) to String using a variety of solutions, e.g. Integer.toString().
Then you can concatenate "v" and your result using a StringBuilder.
Related
input 10100011
output 10 10 00 11 two word separately.
static String getValue(String x){
String y = "";
int getLength = x.length();
if (getLength % 2 == 0){
System.out.println("Length : "+getLength/2);
for (int i = 0; i < getLength/2; i++){
}
}
return y;
}
You can use string operations for this:
for (int i = 0; i < str.length()-1; i+=2){
System.out.print(str.substring(i, i+2) + " ");
}
if(str.length() % 2 != 0)
System.out.print(str.substring(str.length()-1));
This solution uses a StringBuilder1 to append the character to the string being built.
The for loop starts at index 0. In the body of the for loop, it gets the character at index i and i + 1 and appends to the current builder along with a space. On each iteration, i gets incremented by two.
StringBuilder builder = new StringBuilder();
if (getLength % 2 == 0){
System.out.println("Length : "+getLength/2);
for (int i = 0; i < x.length(); i += 2){
builder.append(x.charAt(i))
.append(x.charAt(i + 1))
.append(" ");
}
}
return builder.toString();
1The reason for using a StringBuilder is for performance benefits. Read more about this here.
As per my understanding, you want to print two digits in string separately.
As per 10 10 00 11 this output,
static String getValue(String x){
String y = "";
int getLength = x.length();
System.out.println("Length : "+getLength/2);
for (int i = 0; i < getLength; i++){
if(i%2 == 1) { // this purpose of this check is to make sure this string index starting from 0.
System.out.println(y[i]+" ") // whenever second digit comes it will print space as well to show seperation.
} else {
System.out.println(y[i])
}
}
return y;
}
The task is asking me to insert 2 strings of a very huge number and sum them from right to left like the way we studied in primary school like:
23 + 28 =
(2 + 2 + <1> (this is the left 1 >>> keep reading ))(3 + 8 (give the left <1> from 11 sum with the two front numbers)) =
51.
The algorithm is ok but when I try to do like (just default that the 2 number has the same length so I get lenA and not greater than 10 to make easier):
int len = a.length();
String result="";
for(int i = len; i>0 ; i--) { //<- We only need it to loop how many times
result = Integer.valueOf( a.charAt(len-1) ) + Integer.valueOf( b.charAt(len-1) ) + "" + result;//<<<because we sum them from right to left
lenA--; lenB--;
}
and that (<<<) line always give me the error.
This is just one of a many ways I tried if it's wrong and you have a solution, please just guide me, sometimes i think too much and forgot a lot of small details :))
So the question here is how can i change it from a digit of String to Integer, calculate it and print out String again. But after I read the .charAt() info it said: "Returns the char value at the specified index." so the question maybe confuse between the first question and Convert from a digit from String use charAt -> become Char then convert Char to Integer to calculate and finally convert back to String so that I can + with String result.
I tried a lot of way but still can't solve it.
int lena = a.length();
int lenb = b.length();
int inta[] = new int[lena];
int intb[] = new int[lenb];
int result[];
int carry = 0, maxLen = 0, tempResult;
if(lena >lenb)
maxLen = lena + 1;
else
maxLen = lenb + 1;
result = new int[maxLen];
for(int i = lena - 1; i>=0 ; i--) {
inta[i] = Integer.valueOf( a.charAt(i) );
}
for(int i = lenb - 1; i>0 ; i--) {
intb[i] = Integer.valueOf( b.charAt(i) );
}
for(int i = maxLen - 1; i >= 0; i--) {
result[i] = 0;
}
for(int i = 1; i < maxLen - 1; i++) {
tempResult = 0;
if(lena > i)
tempResult += inta[lena - i];
if(lenb > i)
tempResult += intb[lenb - i];
result[maxSize - i] += tempResult % 10;
result[maxSize - i - 1] = tempResult / 10;
}
String res = "";
for(int i = 0; i < maxLen; i++) {
res += result[i];
}
System.out.println(res);
I think that would do what you want and will avoid most simple mistakes (couldn't try it, no acces to an IDE).
I actually separate the two string into their inside number and then add them into the result tab.
Then I put the result tab into a string that I print.
How do I use the command printf to print my output the same way in the attached output file?
this is my code currently:
else if (args[0].equals("fib")) {
for (int i = 0; i < (Integer.parseInt(args[1]) + 1); ++i) {
System.out.println(getFib(i));
}
}
How do i change it to make it print like the attached picture?
Thank you guys for your help!
Here is an example.
Instead of instant printing add all numbers into a list:
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= number; i++) {
numbers.add(fibonacci(i));
}
Then make a pattern for printf():
String pattern = "%" + (numbers.get(numbers.size()-1).toString().length() + 10) + "d";
where (numbers.get(numbers.size()-1).toString().length() + 10) is the sum of the number of characters in the largest number plus 10 spaces between columns.
Then print all elements of the list. The counter is needed in order to have no more than 6 columns:
int counter = 0;
for (Integer integer : numbers) {
if (counter == 6) {
System.out.println(" ");
counter = 0;
}
System.out.printf(pattern, integer);
counter++;
}
I'm having trouble writing a method that takes a string and counts the number of times the first character (or really any character) appears. The code I've written is below, but for some reason keeps returning half the correct count when I run it. Any help would be appreciated, thanks.
public static void countOccurrences(String string1) {
int counter = 0;
char toCheck = string1.charAt(0);
char compareChar;
for (int i = 0; i < string1.length(); i++) {
compareChar = string1.charAt(i);
if (toCheck == compareChar) {
counter++;
}
i++;
}
System.out.println(toCheck + " appears " + counter + " times in string1.");
}
You're incrementing i twice in each iteration, so you are skipping half the characters:
for (int i = 0; i < string1.length(); i++) { // i is incremented here
compareChar = string1.charAt(i);
if (toCheck == compareChar){
counter++ ;
}
i++ ; // i is incremented again here - remove this line
}
i++ in for loop is incrementing the i value by 1, no need to increment inside th eloop
check Working of For loop here
public static void countOccurrences(String string1) {
int counter = 0;
char toCheck = string1.charAt(0);
char compareChar;
for (int i = 0; i < string1.length(); i++) {
compareChar = string1.charAt(i);
if (toCheck == compareChar){
counter++ ;
}
}
System.out.println(toCheck + " appears " + counter + " times in string1.");
}
Your immediate problem is that i++; happens twice per iteration.
An alternative approach is to use
s.length() - s.replace("x", "").length()
which gives you the number of times "x" appears in s. Arguably it's not the most efficient way, but it's clear.
I'm doing the old Lotto exercise and I need to specifically use an Array[] of integers and not an ArrayList. I have what I thought would work, but I seem to be wrong. I looked for posts similar to these and all of them involved an ArrayList<>. Here is a partition of my code.
Integer[] lottoNums;
lottoNums = new Integer[7];
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
if(i <= 5) {
if(lottoNums[i].equals(lottoNums[i+1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
else if(i >= 1) {
if(lottoNums[i].equals(lottoNums[i-1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
I need to get it to generate a number in between 1 and 59 and not duplicate. I was trying to pair it up with the value stored in the element before and after it (if it had one) and if it was equal to it, it would add 1 to it. I run it a few times and every once in a while im still getting duplicate numbers. How can i do this efficiently, using Arrays[] of integers ONLY?
EDIT:
Initialized array to remove NullPointerException.
Updated Code:
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
}
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt((lottoNums).length-i);
int k = lottoNums[lottoNums.length-i-1];
lottoNums[lottoNums.length-i-1] = lottoNums[rnd];
lottoNums[rnd] = k;
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
//PRINTING LOTTO NUMBERS
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
You can do this by switching the selected number with the last number in the array each time, and then selecting the next from the prefix you have not yet stored:
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt(numbers.length-i);
int k = numbers[numbers.length-i-1];
numbers[numbers.length-i-1] = numbers[rnd];
numbers[rnd] = k;
}
At the end of this loop your selected numbers will be in numbers[numbers.length-7..numbers.length-1], etc.
I would use two arrays. Each time you draw a number see if it exists in the second array. If not use it and add it to the second array.