Printing Binary values using nested loops [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to write a section of code that outputs the binary value up to a user defined number (0-7).
We can't use .toBinaryString it has to be using loops (for loops preferably).
The output should be three columns with filler zeros.
Ex) User enters 7
001
010
100
101
110
111
It seems like it should be so simple but I cant seem to get it right.

for (int i = 1; i <= input; i++) {
String line = "";
for (int k = 2; k >= 0; k--) {
line += ((i >> k) & 1) == 1 ? "1" : "0";
}
System.out.println(line);
}
That uses two for loops.

I would create your own toBinary() function:
int toBinary(int x){
StringBuilder sb = new StringBuilder("");
while(x >= 1){
sb.append(x%2);
x /= 2;
}
return Integer.parseInt(sb.reverse().toString());
}
Then just use that function to print:
for(int i=1; i<=7; i++)
System.out.println( String.format("%03d", toBinary(i)) );

Related

How can i count how many times the keywords user enter is the used in the essay. its doesn't check on the entire keyword [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public static int keywordsChecker(String essay,String key) {
int count = 1;
String[] k=key.split(",");
for (int i = 0; i < k.length-1; i++) {
if (essay.contains(k[i])) {
count++;
}
}
return count;
}
To take into account that each keyword searched for may occur more than once, and to count such occurrences, you may use this inside your for loop:
int indexOfOccurrence = essay.indexOf(k[i]);
while (indexOfOccurrence > -1) {
count++;
indexOfOccurrence = essay.indexOf(k[i], indexOfOccurrence + 1);
}
There are a couple of other issues in your code: I believe you need to initialize count to 0 (not 1). And to count also the last keyword in key your for loop should be for (int i = 0; i < k.length; i++) (without subtracting 1 from k.length). If you want, using <= would also work: for (int i = 0; i <= k.length-1; i++), but this is non-standard, so I would not recommend it.

Why does the modulus not help to find negative odd number? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
What I am doing: Replacing odd numbers(values) in array with zeros.
Problem: when executing following code it replaces only positive numbers, ignoring negative.
Code:
public static int[] nullOddValues(int[] array) {
int[] resultArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
resultArray[i] = 0;
} else {
resultArray[i] = array[i];
}
}
return resultArray;
}
You test the loop variable i for oddity when you (probably) want to test array[i]
if (array[i] % 2 != 0) {
Using modulus on X returns [0-X)
positive X (X > 0) -> it will return 0+
negative X (X < 0) -> it will return 0-
For your problem, I recommend using a bit operator
if((i & 1) == 0)
This will return true for even numbers (positive and negative), since it is checking the last bit of the number.

Adding Elements in an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
items_arr = 4;
System.out.println("The elements in the array are: ");
for (int x = 0; x < items_arr; x++)
System.out.println("Array[" + x + "]=" + array[x]);
System.out.print("\n");
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
for (s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
for (s = 0; s < items_arr; s++)
System.out.println("Array[" + s + "]=" + array[s]);
break;
The output is. The elements are
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Enter an element to Insert: 5
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Array [4]= 0
when I insert 5 it posts 0
any suggestions please.. thanks!
To insert in to the array you shuould be doing follwoing operation
array[s]=input
Two notes here
Arrays are fixed length, and you should be checking the array length before inserting values in to that,other wise you will get ArrayIndexOBException. Safer to sue List/Set
As better coding practise, and to improve the readablity, you should be enclosing the conditional/loop statements (such as if or for) - see eg below
eg: 1
for (int x = 0;x<items_arr;x++) {
System.out.println("Array["+x+"]="+array[x]);
}
eg 2:
for(int s = 0; s < items_arr; s++) {
if (array[s] == input) {
break;
}
}
You have not inserted 5 in your array,
do something after items_arr++
array[ items_arr] = input;
If you do not insert any thing then by default every element is 0
You should be using a Collection type; I would recommend an ArrayList - that is -
List<Integer> al = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
al.add(i);
}
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
al.add(input); // And so on...
You are not updating/inserting the array with the new input.
for(s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
just replace the above code with
array[ items_arr] = input;
items_arr++;

The value of the loop counter of a for loop is one larger than I expect after exit from the loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a simple for loop, which lets the loop counter, i go up to 5.
int i;
double n = 1 / 2;
for (i = 2; i <= 5; i++) {
n = n + 1.0 / i;
}
System.out.print(i);
So I expect the value of the counter to be 5 after the loop finishes. But the value is 6, nit 5. Why is that?
Thanks
Because you are incrementing i value as i++ in for{..} loop
for (i = 2; i <= 5; i++)
^ here
In for loop after checking the condition, body part will be executed
after that increment or decrement will be done
Process will be
<----
1step 2step 4step
for (i = 2; i <= 5; i++){
/*body part*/
3step
}
After 4th step it will moves to check 2nd step i.e. condition part
So thats why it prints the i value as
6
The for loop:
for (i = 2; i <= 5; i++) {
// code
}
which has condition i <= 5 and the condition will be false when i = 6 and the loop breaks, goes to the print line.
Thanks for reminding me my first time programming experience, When I used to write a code a = 5 and printed it to see what it shows in the console. :)
The i++ is the same as saying i = i + 1. In this case you can also use ++i and get the same result.

For loop results reverse of expected order [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The problem is I have a for loop in android , and its seems to be running in the reverse order.
Here is the code :
for(i=0;i<strlent;i++)
{
//ch=st.charAt(i);
//disp(String.valueOf(ch));
disp(String.valueOf(i));
}
I have a string and would like to get each characters out of it, but if I feed in "babe" it runs e-b-a-b. I checked the i value and it runs as 3-2-1-0. I seriously don't understand why it behaves this way.
This is my disp function
public void disp(String st) // this function is used to check with message boxes
{
AlertDialog.Builder adb = new Builder(this);
adb.setTitle("Testing");
adb.setMessage(st);
adb.show();
}
String str = "Let Me Reverse";
System.out.println("\nIn order..");
for(int i = 0; i < str.length(); i++){
System.out.print(str.substring(i, i + 1));
}
System.out.println();
for(int i = 0; i < str.length(); i++){
System.out.print(str.charAt(i));
}
System.out.println();
for(char ch : str.toCharArray()){
System.out.print(ch);
}
System.out.println("\nIn reverse order..");
for(int i = str.length() - 1; i >= 0; i--){
System.out.print(str.charAt(i));
}
String name = "Hello";
for(int i=name.length()-1;i>=0;i--){
System.out.println(name.charAt(i));
}

Categories

Resources