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 6 years ago.
Improve this question
EDIT: Since there are claims that this is a duplicate question, I will state my stance on why it is not.
The other question had posed a problem regarding the conversion of a string input to an integer (the answer deemed correct). This is irrelevant here, as the problem in my case is one of logic.
The solutions on the other question cannot correct the problem this question presents (finding the syntactical "charAt" error).
Frankly, the context of the other question is beyond the scope of my knowledge in Java.
I have successfully created a program that converts binary numbers to decimal numbers.
import java.util.Scanner;
public class ProblemThree // to convert binary to decimal
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
int[] number = new int[length];
int[] powerTwo = new int[length];
// To list every digit separately //
for (int n = 0; n <= length - 1; n++)
{
number[n] = (int) (binary / Math.pow(10, n)) % 10;
}
// To set the values in powerTwo to 2 //
for (int n = 0; n <= length - 1; n++)
{
powerTwo[n] = 2;
}
// To update the values in powerTwo //
for (int n = 0; n <= length - 1; n++)
{
if (n == 0)
powerTwo[0] = 1;
else if (n == 1)
powerTwo[1] = 2;
else
powerTwo[n] *= powerTwo[n-1];
}
// To add if current value is 1 //
for (int n = 0; n <= length - 1; n++)
{
if (number[n] == 1)
answer += powerTwo[n];
}
System.out.println(powerTwo[0]); // for testing
System.out.println(number[0]); // for testing
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
Seeing how some of the steps were redundant, I tried to simplify the code.
import java.util.Scanner;
public class ProblemThreeTestFunction
{
public static void main (String[]args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter binary");
int binary = scan.nextInt();
int answer = 0;
int length = String.valueOf(binary).length();
String number = String.valueOf(binary);
for (int n = 0; n <= length - 1; n++)
{
if (number.charAt(n) == 1)
answer += (int)Math.pow(2, n);
}
System.out.println("The decimal version of " + binary + " is " + answer + ".");
}
}
I actually have no idea why the simplified code logic does not work. It uses the same concept as my original.
Thanks in advanced!
Why don't you just use:
int decimalValue = Integer.parseInt(binary, 2);
But if you use this you Need to use scan.nextLine() not scan.nextInt().
This will just convert your binary number to decimal using base 10 like seen here.
You need to test against the character '1':
if (number.charAt(n) == '1')
not the number 1 that you are currently doing:
if (number.charAt(n) == 1) // WRONG!
Also, since charAt counts from the left, and binary expansion counts from the right, you need to reverse the sense. Change
Math.pow(2, n)
to
Math.pow(2, length - 1 - n)
You are comparing with digit 1, it should be character 1 i.e. '1'.
for (int n = 0; n <= length - 1; n++) {
if (number.charAt(n) == '1') {
answer += (int)Math.pow(2, length - n - 1);
}
}
Also you need to correct the exponent part.
Related
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 3 years ago.
Improve this question
For any given dimension (here I just set it to 8 to make it easy) I want to print out the letters with odd indexes. So I am trying to get an output like: B D F H... and other letters depending on the dimension). I put a while loop to make the row 0 since I only want to print out the the odd letters on the first row and then inside the while loop I added a for loop to print out the columns (letters) with odd n. However I am getting a not an error:
error: not a statement
for (n = 1; n<dimension; n +2){
^
I am also unsure of where to put the loops to print out the odd letters.
This is my code so far:
public static void main(String[] args) {
int dimension = 8; // normally any given dimension (int dimension = Integer.parseInt(args[0]))
int n = dimension - 1;
int m = dimension -1;
char [] alphabet = {'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'};
int [] nums = new int [dimension];
for (int i = 0; i < dimension; i ++) {
nums [i] = i + 1;
}
int [] [] position = new int [dimension] [dimension];
for (int row = 0; row < dimension; row ++) {
for (int col = 0; col < dimension; col ++) {
position [row] [col] = alphabet[col] + nums[row];
}
}
char p = (char)(position[m][n] - nums[n]);
while (m == 0) {
for (n = 1; n<dimension; n +2){
System.out.println(p); //odd letters on the first row
}
}
}
}
Edit: the program is compiling but the loop is not working so I am not getting any output. How can I fix it?
This is a simple syntax error.
for (n = 1; n<dimension; n +2){
Should be:
for (n = 1; n<dimension; n += 2){
The final part of the for statement is an operation that can be used to change the iterator (or do other operations). If you consider the following line of code:
n +2;
This is not a valid statement by itself. However, the following statement is valid:
n += 2;
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 6 years ago.
Improve this question
import java.io.*;
import java.util.*;
public class Binary {
public static void main(String args[]) {
int i = 0, j = 0, num;
Scanner in = new Scanner(System.in);
int arr[] = new int[100];
System.out.println("enter the number");
num = in.nextInt();
while (num != 1) {
j = num % 2;
num = num / 2;
arr[i] = j;
i++;
}
for (i = i; i <= 0; i--) {
System.out.print("The binary number: " + arr[i]);
}
}
}
I wrote this programme to convert decimal input to its corresponding binary value, the programme takes the input but it does not show the output i.e. the binary value. please help
As it was already pointed out, you need to change the condition of
while (num != 1) {
to
while (num > 0) {
since your version is prone to an infinite cycle due to the possibility of num being 2.
Change the for cycle, like this:
for (i = arr.length - 1; i >= 0; i--) {
System.out.print("The binary number: " + arr[i]);
}
but to be able to do this, you need to know how many elements will you need to use, so change the declaration of arr to this
int arr[] = new int[(int)Math.ceil(Math.log(num) / Math.log(2))];
But to be able to do this, you need to initialize num before you declare arr. Code is untested, let me know if there are any typos.
condition should be while(num!=0){ //do calculations}
and change the condition of for loop into for(i=i;i>=0;i--){}
You could use the Integer class and it's static method toBinaryString(int i). This method converts an int into its binary value and returns it as a String.
If I correctly understood what you are trying to achieve, you could just write:
Scanner in = new Scanner(System.in);
System.out.println("enter the number");
int num = in.nextInt();
String binary = Integer.toBinaryString(num);
System.out.print("The binary number: " + binary);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I have this code in java and i want to convert it into php. With this function i want to format some data and write them in a txt file.
Is there any classes as the text class in java to handle it?
here is the code :
public static void printAll(int n1, int n2, double[][] m,
String[] labs, double scaling, JTextArea outext)
{
// Some definitions for handling output formating
NumberFormat myFormat = NumberFormat.getNumberInstance();
FieldPosition fp = new FieldPosition(NumberFormat.INTEGER_FIELD);
// Following suppresses e.g. comma in 1,000 = 1000 for English locale.
myFormat.setGroupingUsed(false);
int w;
double maxval;
maxval = SMALL;
for (int i =0; i < n1; i++) {
for (int j =0; j < n2; j++) {
// Scale up values by 'scaling' factor
if (m[i][j] > maxval) maxval = m[i][j];
}
}
String temp = myFormat.format(maxval*scaling,
new StringBuffer(), fp).toString();
// Output display field width of each number: extra 2 to
// account for possible minus sign, and 1 space.
w = fp.getEndIndex() - fp.getBeginIndex() + 2;
// System.out.println(" Output field width = " + w);
// In the next few lines we say how we want numbers to appear.
// max integer digits = max no. of digits before dec. point
// max fraction digits = max no. of digits following dec. point
// min fraction digits = min no. of digits following dec. point
myFormat.setMaximumIntegerDigits(w);
// We will set min and max nos. of digits following dec. point to 0
myFormat.setMaximumFractionDigits(0);
myFormat.setMinimumFractionDigits(0);
for (int i=0; i<n1; i++)
{
// First handle cols for labels, QLT, PDS, INR:
String myString = labs[i];
myString = getSpaces(4 - myString.length()) + myString;
outext.append("|" + myString + "|");
for (int j = 0; j < 3; j++) {
String valString = myFormat.format(
scaling*m[i][j], new StringBuffer(), fp).toString();
// With a max field width of w, we pack spaces before val.
valString = getSpaces(4 - fp.getEndIndex()) + valString;
outext.append(valString);
}
// Print each row, elements separated by spaces
for (int j = 3; j < n2; j++)
{
// Scaling is in thousandths; but note if +ve only.
w = 4; // All cntr and corr are positive.
if (j/3 == (double)j/3.0) { // Here, will handle proj.
outext.append("|");
w = 5; // Allow for -ve vals.
}
String valString = myFormat.format(
scaling*m[i][j], new StringBuffer(), fp).toString();
// With max field width of w, we pack spaces before val.
valString = getSpaces(w - fp.getEndIndex()) + valString;
outext.append(valString);
}
outext.append("|");
// Start a new line at the end of a row
outext.append("\n");
}
}
Yes, you can do this function using PHP. There is no built-in function that does this, so you must code it yourself
I suggest you start breaking the function down into pieces and try using some PHP code, then if you get stuck search for that specific question before you post.
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 8 years ago.
Improve this question
I have an assignment on arrays I'm working on and one of the questions is to write a code for a histogram.
The method histogram takes a positive number n indicating the number of divisions in which the span of the data is divided, and returns an array of integers of length n, where each element of the array contains the count of the elements that fall into this
division.
For example, if the data is (0:5; 1:2; 2:4; 9:8; 5:1; 10:5), then its span is
10:0 (from 0:5 to 10:5).
histogram(4) would divide this range into four segments:
0.5—3.0, 3.0—5.5, 5.5—8.0, and 8.0—10.5.
Inspecting the data, we see that 3 values fall in the first segment, 1 value in the second, 0 values in the third, and 2 values in the fourth. Therefore, the returned value is an array of length 4 containing the values (3; 1; 0; 2) in that order.
Note that the sum of the elements in the returned array is equal to the number of
elements in the data array.
here is my code:
#Override
public int[] histogram(int divisions) {
int[] range = new int[divisions];
double segment = span() / divisions;
for (int i = 0; i < data.length; i++) {
if (data[i] <= (smallestElement() + segment)) {
range[0] += 1;
}
if (data[i] <= (smallestElement() + (2 * segment))) {
range[1] += 1;
}
if (data[i] <= (smallestElement() + (3 * segment))) {
range[2] += 1;
}
if (data[i] <= (smallestElement() + (4 * segment))) {
range[3] += 1;
}
}
return range;
}
and here is my Junit test for my method:
#Test
public void testHistogram() {
double[] data = new double[3];
data = new double[]{0.5, 1.2, 2.4, 9.8, 5.1, 10.5};
int[] dat = new int[4];
dat = new int[]{3, 1, 0, 2};
DoubleArrayStatisticalOutcomes x = new DoubleArrayStatisticalOutcomes(data);
assertArrayEquals(dat, x.histogram(4));
}
the test is not passing. can someone tell me what I did wrong ?
You are incrementing all the histogram bins for each value. In your for loop, if a value is less than smallestValue() + segment, all the conditional statements are executed, not just the smallest it matches.
This makes your histogram cumulative. There are four elements total in the first two bins.
Add a continue statement in each if or make if 2-4 into else ifs.
Your function also breaks down the moment you pass a value not equal to 4 as the tests are hardcoded. Try something like (untested):
double lowerBound = smallestElement();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < divisions; j++) {
if (data[i] <= (lowerBound + (j+1) * segment)) {
range[j] += 1;
continue;
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
if a input a number, how do i count the multiples of that inputted number until 100.
For example if i input the number 8
It would print out 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96
You can modify a for loop very nicely so that it only increments by the number that you want. The upside is that it is not only easy to follow, and shorter, but it is also more efficient. Don't loop more times than you need. Keep it simple.
Eg
int n = 8;//your chosen number (however you decide to get it)
for (int x = n; x <= 100;x+=n)
{
System.out.println (x);
}
What we have done:
made an int n holding the number that the user wants to increment by.
Then in the for loop, we:
Made the for loop variable,x equal to n.
Made the condition that the loop must break once x reaches or passes 100
Tell the loop to increase x by n for every iteration.
You can use a for loop starting from 8, and at each iteration add 8 to the current number. I let you fill up the ??? :
for (???; value <= 100; ???) {
System.out.print(value);
}
Here's also a one-liner using java 8 :
IntStream.iterate(8, i -> i+8).limit(100/8).forEach(System.out::println);
The most basic way is to use a for loop
public static void printMultiples(int k) {
boolean isHead = true;
for (int i = 0; i < 100; i++) {
if (i % k == 0) {
if (isHead) {
System.out.print(i);
isHead = false;
}
else System.out.print(", " + i);
}
}
}
Use this. It will not use java 8, as that is very new, so its not recommended.
public class MyClass {
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("You must enter at least one number!");
}
int originalNumber = Integer.parseInt(args[0]);
int number = originalNumber * 1; // For avoiding pointer problems
while((number + originalNumber) > 100) {
System.out.println(number);
number += originalNumber;
}
}
}
Here:
import java.util.Scanner;
Scanner input = new Scanner(System.in);
int i = n;
System.out.println("Enter number: ");
int n = input.nextInt();
while (true) {
System.out.println(i);
i += n;
if (i > 100) break;
}
int input = 8;
int result = input;
while(result < 100){
System.out.println(result);
result += input;
}
You can use the modulo operator %:
if (n % 8 == 0) {
System.out.println(n);
}
This means: if the remainder of dividing n by 8 is equal to 0, we should print this number.