Attempting to convert string of numbers to binary with this code
public static int convert(String text)
{
int num =0;
for(int i =0; i<text.length();i++)
{
if(((int)text.charAt(i)>=48)&&((int)text.charAt(i)<=59))
{
System.out.println("Before: i = " + i + " num = "+ num+" char = "+ text.charAt(i) + "numchar = " + ((int)text.charAt(i)-48));
num = num*10 + ((int)text.charAt(i)-48);
System.out.println("After: i = " + i + " num = "+ num+" char = "+ text.charAt(i) + "numchar = " + ((int)text.charAt(i)-48));
}
}
return num;
}
}
However once it reaches its 10th number the output becomes a complete jumble with negative numbers and random numbers, even when my test strings are binary. Any idea why this could be happening?
The int datatype in Java is a 32-bit signed integer, so the maximum value it can represent is 2^31 - 1 = 2147483647. Since you are trying to parse numbers bigger than this, your arithmetic will result in integer overflow.
To solve this problem you will need to use a datatype which can represent larger integers, such as long (up to about 19 digits) or BigInteger (arbitrarily large).
Related
First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n
So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1
I am trying to figure out how to find the percent difference between the original (no space) string of text and the disemvoweled (no space) string of text. I am attempting to do this by using the equation ((newAmount-reducedAmount)/reducedAmount) but I am having no luck and am ending up with a value of zero, as shown below.
Thank you!
My Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
System.out.println("Welcome to the disemvoweling utility!"); // Initially typed "disemboweling" xD
System.out.print("Enter text to be disemvoweled: ");
String inLine = console.nextLine();
String vowels= inLine.replaceAll("[AEIOUaeiou]", ""); // RegEx for vowel control
System.out.println("Your disemvoweled text is: " + vowels); // Prints disemvoweled text
// Used to count all characters without counting white space(s)
int reducedAmount = 0;
for (int i = 0, length = inLine.length(); i < length; i++) {
if (inLine.charAt(i) != ' ') {
reducedAmount++;
}
}
// newAmount is the number of characters on the disemvoweled text without counting white space(s)
int newAmount = 0;
for (int i = 0, length = vowels.length(); i < length; i++) {
if (vowels.charAt(i) != ' ') {
newAmount++;
}
}
int reductionRate = ((newAmount - reducedAmount) / reducedAmount); // Percentage of character reduction
System.out.print("Reduced from " + reducedAmount + " to " + newAmount + ". Reduction rate is " + reductionRate + "%");
}
}
My output: (Test string is without quotes: "Testing please")
Welcome to the disemvoweling utility!
Enter text to be disemvoweled: Testing please
Your disemvoweled text is: Tstng pls
Reduced from 13 to 8. Reduction rate is 0%
You used an integer data type while calculating percentage difference while performing integer division. You need to type cast one of the variables on the right hand side of the equation to perform double division and then store them in double. The reason for doing this is java integer type can't hold the real numbers.
Also, multiple it by 100 to get the percentage.
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);
If you want a fraction between 0 and 1, then
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);
Your formula gives you a value between zero and one.
An integer cannot hold fractions so it always shows zero.
Multiply by 100 to get a regular percentage value.
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reduction
I'm getting a number from an addition of Int and then put it as String. I need to know what is the first, second etc. number of the addition. For example the number is 7654, how to know that "7" is the first number? And "6" the second? etc.
String result += "\nThe result of addition"
+ String.valueOf(add_1) + "+" + String.valueOf(add_2)
"+ is" + String.valueOf(int_result);
I want to know the number of a determinate position of the String that contain the result.
The string is String.valueOf(int_result), I can use directly int_result too.
Thanks!
Just walk each character in the resulting string:
String result = String.valueOf(int_result);
for (int i=0; i< result.length(); i++) {
char c = result.charAt(i);
System.out.println("Digit " + i + " = " + c);
// And if you need this as an integer
int digit = Integer.parseInt(""+c);
}
In Java to get the character at a particular position in a string just use this
String number ="7564";
char c = number.charAt(0);
The above code will asign '5' to char variable c. You can further parse it to integer by doing this
int i = Integer.parseInt(c);
I got this code that fetches floats from a database.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += String.valueOf(ing.getAmount()) + " " +
ing.getUnit() + " " + ing.getIngredient() + "\n";
}
The database is written in REAL values as some of them is 1.5, 2.5, 1.4 etc. But we also have these whole numbers without the need of a decimal, such as 1, 4, 10 etc.
The problem is that the database table needs to be in REAL value, which gives us no choice but to give all the values one decimal, no matter if it's needed or not.
So we'll end up with values like:
1.0
1.5
2.3
20.0
5.0
My question is: How do we remove the unnecessary decimals, but keep the ones that need it?
One very simple way to remove these would be to strip the characters using StringUtils.
String displayValue = String.valueOf(ing.getAmount());
displayValue = StringUtils.stripEnd(displayValue, ".0");
For an input of "1.0", "1" will be returned.
A more technical approach would be to use the modulus operator %
For example:
if(value%1 == 0){ //1 divides into number perfectly, there is no decimal
//cast value to integer or another non decimal variable
} else {
//use existing value as it contains a decimal
}
How about this (does't require any fancy things like StringUtils)?
String s = String.valueOf(1.0);
System.out.println(s);
/* Make this block as a function and return an int */
String ss = " ";
if (s.charAt(s.length()-2) == '.' && s.charAt(s.length()-1) == '0'){
ss = s.substring(0,s.length()-2);
System.out.println(ss);
}
/**************************************************/
int converted = Integer.parseInt(ss);
System.out.println(converted);
}
If you want to make it a function block, you can.
You can check it working on IDEONE - http://ideone.com/udJv8M
Check the float values with modulo. If 0 is returned it is an Integer. Here is an example with the numbers you have mentioned:
List<Float> values = new ArrayList<Float>();
values.add(new Float(1.0f));
values.add(new Float(1.5f));
values.add(new Float(2.3f));
values.add(new Float(20.0f));
values.add(new Float(5.0f));
List<String> strValues = new ArrayList<String>();
for(Float value : values)
{
String strValue = "";
if(value % 1 == 0)
{
Integer intValue = value.intValue();
strValue = intValue.toString();
strValues.add(strValue);
}
else
{
strValue = value.toString();
strValues.add(strValue);
}
System.out.println(strValue);
}
You can use a custom DecimalFormat pattern:
public static String customFormat(String pattern, double value) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
return myFormatter.format(value);
}
Then a pattern of # defines places holders for optional digits, so #.### will give up to 3 digits where necessary only.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += customFormat("#.###", ing.getAmount()) +
" " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
So don't convert your data to a String except for display only. Real numbers can represent both integers and floating point numbers using the same data type. Plus if you ever needed to do any math on your numbers you can't use Strings to do that. If you convert your numbers from the database directly to String before storing them into Ingredient then you've screwed yourself later on if you want to do calculations on those numbers. (Say you wanted to add a feature to double a recipe and have all of the quantities change for the user). Under your current plan you're preventing yourself from doing something like that because you're overly focused on the display of that number.
Instead just create a method on Ingredient to convert your numbers using String.format(). Like so:
public class Ingredient {
private double amount;
private String name;
public String asDecimal() {
return String.format("%.1f", amount);
}
public String asInteger() {
return String.format("%.0f", amount);
}
public String asFraction() {
// exercise left to the reader
}
}
You could even add a function that converts decimals to fractional amounts to make it easier to display things chiefs might understand vs decimals which are harder. Bear in mind String.format() will round floating point amounts (0.5 -> 1 using as Integer).
Convert your String returned from ing.getAmount() to a Float object, then use the modulo function to determine whether your value is an exact multiple of 1 (ie no decimal places). If so, convert your Float object to an int, which will concatenate the decimals.
Float f = Float.valueOf(ing.getAmount());
if(f%1 == 0) {
// Use f.intValue() to concatenate your decimals.
ingredients +=String.valueOf(f.intValue() + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
else {
ingredients +=String.valueOf(ing.getAmount()) + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
I hope this helps.