Have an assignment that requires me to take an input from the user of a series of numbers. ex.(1 12 -34 9) I am then asked to determine the number of positive and negative numbers. The class has not gotten into any of the "easy" solutions to this problem such as arrays, string.split(), buffers etc... The most advanced methods taught are the use of loops. My question is how can I take the string line of numbers and separate them individually without the aforementioned methods? I can take it the rest of the way I am certain without complications but this one step has me at a loss. Any input will help. Thanks
Presumably you start with a string containing all the numbers - I'll call it numString.
Then:
ArrayList<String> numbers = new ArrayList<String>();
String aNumber = "";
for (int i = 0; i < numString.length(); i++){
String letter = numString.substring(i, i+1);
if (letter.equals(" ")){
numbers.add(aNumber);
aNumber = "";
}
else{
aNumber += letter;
}
}
ArrayList<String> negatives = new ArrayList<String>();
ArrayList<String> positives = new ArrayList<String>();
for (String s : numbers){
if(s.contains("-")){
negatives.add(s);
}else{
positives.add(s);
}
System.out.println("There were " + positives.size() + "positive numbers.");
System.out.println("There were " + negatives.size() + "negative numbers.");
System.out.println("Making a total of " + numbers.size() + "numbers.");
Of course, I'd only recommend this solution in the context of what you've learned. This wouldn't be the best way to do this otherwise.
Good luck!
edit - Alternatively - quicker but more logically complex option:
There should be as many "-" as negative numbers, and one less space than total numbers - and as many positive numbers as totalCount minus negativeCount.
So in pseudocode:
NegativesCount = count("-");
PositivesCount = count(" ") + 1 - NegativesCount;
and in code:
int dashCount = 0;
int spaceCount = 0;
for (int i = 0; i < numString.length(); i++){
String letter = numString.substring(i, i + 1);
if (letter.equals(" ")){
spaceCount++;
}
else if(letter.equals("-")){
dashCount++;
}
}
int negCount = dashCount;
int posCount = spaceCount - 1 + dashCount;
System.out.println("There were " + posCount + "positive numbers.");
System.out.println("There were " + negCount + "negative numbers.");
System.out.println("Making a total of " + spaceCount + "numbers.");
It has come to my attention that the confusing way in which the assignment is worded combined with the misleading example of the running program led me to believe the numbers were entered all at once when in reality the numbers are to be prompted for one at a time. I can easily write the program that handles THIS method. Thanks to all of the responses and I apologize for a question that leads to nowhere. Just so you don't think I am crazy here is the "example" of the program running as it should provided in the assignment:
Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
Notice how the input looks as though it is a one line entry -_-
The best way to do this is by using regex.
You can count the instance of followed by -ve sign to count number of negative integers. and count instance of followed by numerical value to count number of positive integers.
Related
I am working on a program right now and part of it requires me to find the total amount of digits between two integers, I have figured it out for integers that have the same amount of digits, e.g. 1234 and 4980 (both have four digits) but I can't seem to figure it out for the integers that don't have the same amount of digits, i.e. 3 and 5698 (3 only has one digit and 5698 has four). How might I go about this?
Boy, the algorithm is not obvious – your last comment is rather crucial.
Evidently this question boils down to:
For each 'number' between the 2, including both of the edges, count how many digits that number has.
Sum those up.
For your example it's simply (4980 - 1234 + 1) * 4 = 14988.
Sounds like you simply need to for-loop: for (int i = 1234; i <= 4980; i++), and then for each i just figure out how many digits there are and add those.
An straightforward way is to use logarithms. The number of digits in an integer n is (int)Math.log10(n)+1. Assuming you are doing inclusive computations on first thru last it would be as follows:
int sum = 0;
int first = 3;
int last = 3333;
for (int i = first; i <= last; i++) {
sum += Math.log10(i)+1;
}
System.out.println(sum);
prints
12223
But a more efficient and perhaps less obvious way it to forgo logs and simply compute in pieces. This will reduce number of iterations of the loop. This works by computing the number of digits and the power in increments. I put in print statements so you can see the progression.
int digits = 1;
int power = 10;
int limit = last;
sum = 0;
while(power < limit) {
if (power > first) {
sum += (power - first) * digits;
System.out.println(power + " " + first + " " + digits + " : partial running sum = " + sum);
first = power;
}
digits++;
power*= 10;
}
sum += (limit - power/10 + 1)*digits;
System.out.println(limit + " " + power/10 + " " + digits + " : partial running sum = " + sum);
System.out.println(sum);
prints
10 3 1 : partial running sum = 7
100 10 2 : partial running sum = 187
1000 100 3 : partial running sum = 2887
3333 1000 4 : final sum = 12223
12223
I am trying to add two parts of an array together to go into an int value. I am using Luhn algorithm to figure out of a credit card is a valid credit card. We are only using 6 digit credit card's just to make sure no one enter's a real credit card number. The part I am confused on is when I go to split a number that is above 10 and add it together. Example if the algorithm was to give me 12 I would need to separate it into 1 and 2 and then add them together to equal 3. I believe I am splitting it currently in the code but when I go to add them together I get some number that makes no since. here is a section of the code with some notes about it.
I have printed out numbers in certain places to show myself what is going on in certain places. I have also added in some comments that say that either the number that is printed out is what is expected, and some comments for when there isn't something I expected
int[] cardNumber = new int[]{ 1,2,3,4,5,5};
int doubleVariablesum = 0;
int singleVariablesum = 0;
int totalSum = 0;
int cutOffVar = 0;
String temp2;
for (int i = cardNumber.length - 1; i >= 0;) {
int tempSum = 0;
int temp = cardNumber[i];
temp = temp * 2;
System.out.println("This is the temp at temp * 2: " + temp);
temp2 = Integer.toString(temp);
if (temp2.length() == 1) {
System.out.println("Temp2 char 0: "+ temp2.charAt(0));
// this prints out the correct number
// Example: if there number should be 4 it will print 4
tempSum = temp2.charAt(0);
System.out.println("This is tempSum == 1: " + tempSum);
// when this goes to add temp2.charAt(0) which should be 4 it prints out //something like 56
} else {
System.out.println("TEMP2 char 0 and char 1: " + temp2.charAt(0) + " " + temp2.charAt(1));
// this prints out the correct number successfully spited
tempSum = temp2.charAt(0) + temp2.charAt(1);
System.out.println("This is tempSum != 1: " + tempSum);
// but here it when I try to add them together it is giving me something
// like 97 which doesn't make since for the numbers I am giving it
}
doubleVariablesum = tempSum + doubleVariablesum;
System.out.println("This is the Double variable: " + doubleVariablesum);
System.out.println();
i = i - 2;
}
Since you are converting the number to a string to split the integer, and then trying to add them back together. You're essentially adding the two characters numerical values together which is giving you that odd number. You would need to convert it back to an integer, which you can do by using
Integer.parseInt(String.valueOf(temp2.charAt(0)))
When adding char symbols '0' and '1' their ASCII values are added - not numbers 0 and 1.
It is possible to use method Character::getNumericValue or just subtract '0' when converting digit symbol to int.
However, it is also possible to calculate sum of digits in a 2-digit number without any conversion to String and char manipulation like this:
int sum2digits = sum / 10 + sum % 10; // sum / 10 always returns 1 if sum is a total of 2 digits
Seems like charAt() type casts into integer value, but the ascii one. Hence for the characters '0' and '1', the numbers 48 and 49 are returned resulting in a sum of 97. To fix this, you could just assign temp2 to (temp / 10) + (temp % 10). Which actually splits a two digit integer and adds their sum.
You need to be aware of the following when dealing with char and String
Assigning the result of charAt(index) to an int will assign the ASCII value and not the actual integer value. To get the actual value you need to String.valueOf(temp2.charAt(0)).
The result of concatenating chars is the sum of the ASCII values.
eg if char c = '1'; System.out.println(c + c); will print "98" not "11".
However System.out.println("" + c + c); will print "11". Note the "" will force String concatenation.
This question already has answers here:
A java console program that converts decimal to binary without using a predefined method (for)
(2 answers)
Closed 6 years ago.
I made a java console program that prints the decimal value of the binary value inputted. Now, I have a problem with my program that
for e.g. output:
Enter input = 10011101 then the binary value is 3534200 instead of 157
After surfing the internet for the formula in converting binary value to decimal, this is the reference I took for making this program.
1*2^7 + 0*2^6 + 0*2^5 + 1*2^4 + 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0 = 157.
I tried the long version in making this program, in using for loop... I guess that's a dumb challenge? haha!
here's the code(w/ comments!):
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num = Integer.parseInt(new String(b.substring(b.length() - 1).trim()));
//num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
for(int a = i; a > 0; a--){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
num = Integer.parseInt(new String(b.substring(i - 1).trim())); //uhm dunno how to describe this, but you'll see
power = 2;
}
System.out.print(formula);
}
}
ever since I started using java, this is the only thing that I know. (refer to my last question since sep 4)
please help :(
You have a number of problems:
1) Integer.parseInt(new String(binary).trim()) does not do what you think it does. Therefore, your num is wrong.
2) You calculate your power wrong.
3) A general advice, put some empty lines to separate your code into small blocks that make sense. It will be easier on the eyes.
The fixed program should look like this:
public static void main(String[] args) throws IOException {
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num; //num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
power = 1;
num = Integer.parseInt(Character.toString(b.charAt(i-1)));
for(int a = i; a < b.length(); a++){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
}
System.out.print(formula);
}
Write statements that can be used in a Java Program two integers and display the number of even integers that lie between them. For example, the number of even integers that lie between 12 and 5 are 4
So far below is what i have.... the program outputs all the numbers between the two integers, and not the actual number of even integers.
Can someone please help / tell me what i am doing wrong ?
import java.util.Scanner;
public class evenNumberPrinter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the smaller integer");
int numOne = keyboard.nextInt();
System.out.println("Enter the larger integer");
int numTwo = keyboard.nextInt();
for (int i = numOne; i <= numTwo; i++) {
System.out.println(i + " ");
}
}
}
to calculate count of even numbers you don't have to use for loop, here is the formula:
static long evenCount(long a, long b) {
return ((Math.abs(a - b) + 1) >>> 1) + ((~((a & 1) | (b & 1))) & 1);
}
some clarification:
zero (0) is even number
count of even numbers obviously depends on distance between two values, lets pull some data:
0-0 - 1 number, distance 0 (0)
0-1 - 1 number, distance 1
0-2 - 2 numbers, distance 2 (0, 2)
0-3 - 2 numbers, distance 3
0-4 - 3 numbers, distance 4 (0, 2, 4)
0-5 - 3 numbers, distance 5
0-6 - 4 numbers, distance 6 (0, 2, 4, 6)
1-1 - no even, distance 0
1-2 - 1 number, distance 1 (2)
so, count of even numbers is determined by (distance+1)/2 plus one if both numbers are even
so, if we take distance Math.abs(a-b) + 1 divide it by two (>>>1) and then add 1 if and only if both numbers are even (a&1)==0
Another solution is to use pure math:
round the smaller number to the next even number (e.g. 5 to 6)
round the bigger number to the previous even number (e.g. 13 to 12)
subtract from the bigger rounded the smaller, e.g. 12-6 = 6
since even numbers are every second, divide it by 2 plus add one to count the first number of the range as well, that is 3+1=4
That is:
public static void main(final String[] args) {
final int number1=1;
final int number2=6;
int min=Math.min(number1, number2);
int max=Math.max(number1, number2);
min=min+min%2; // round up
max=max-max%2; // round down
final int evens=(max-min)/2+1; // even range plus the first number
System.out.println(evens); // Look ma, no loops
}
Edited to include explanation
Your for loop is doing nothing more than printing each number between numOne and numTwo. What you want to do is check to see if i is even or odd which can be accomplished using the modulus operator if i modulus 2 equals zero, then that number is even, and you should increment a counter variable each time this is true.
Change your for loop to something like this:
int evenCounter = 0;
for (int i = numOne; i < numTwo; i++){
if (i % 2 == 0){
System.out.print(i + " ");
evenCounter++;
}
}
System.out.println("There are " + evenCounter + " even numbers between " +
numOne + " and " + numTwo);
A little more optimal solution (if you want to print the numbers). Testing for parity (odd vs even) can be done only once, before entering the loop. Afterwards, just stay on even numbers by incrementing by 2.
int n = numOne;
int evenCount = 0;
if ((n%2)==1) { n++; }
while (n <= numTwo) {
System.out.println(n);
n += 2;
evenCount ++;
}
System.out.println( "There are " + evenCount + " even numbers between " + numOne + " and " + numTwo );
However, if your goal is only to determine how many there are (not print them), this is not optimal. A mathematical solution will be much faster.
int n = 0; //this is your counter
for (int i = numOne; i < numTwo; i++) { //use < numTwo instead of <= numTwo
//so it doesn't count numTwo as an int between your range
if (i%2 == 0) {n++;} //checks to see if number is even
// if it is, it adds one to the counter and moves on
}
System.out.println("there are " +n+ "even numbers between " +numOne+ " and " +numTwo); //prints out how many even ints were counted.
I'm new to Java and also new to while, for, and if/else statements. I've really been struggling with this beast of a problem.
The code and description is below. It compiles, but I'm it doesn't calculate as expected. I'm not really sure if it's a mathematical logic error, loop layout error, or both.
I've been grinding my gears for quite some time now, and I'm not able to see it. I feel like I'm really close... but still so far away.
Code:
/*
This program uses a while loop to to request two numbers and output (inclusively) the odd numbers between them,
the sum of the even numbers between them, the numbers and their squares between 1 & 10, the sum of the squares
of odd numbers.
*/
import java.io.*;
import java.util.*;
public class SumOfaSquare
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int firstnum = 0, secondnum = 0, tempnum = 0;
int sum = 0,squaresum = 0, squarenum = 0;
int number = 1;
String oddOutputMessage = "The odd numbers between" + firstnum + " and " + secondnum + " inclusively are:";
String evenSumMessage = "The sum of all even numbers between " + firstnum + " and " + secondnum + "is: ";
String oddSquareMessage = "The odd numbers and their squares are : ";
String squareMessage = "The numbers and their squares from 1-10 are : ";
System.out.println ("Please enter 2 integers. The first number should be greater than the second: ");
firstnum = console.nextInt();
secondnum = console.nextInt();
//used to find out if first number is greater than the second. If not, inform user of error.
if (firstnum > secondnum)
{
tempnum = firstnum;
System.out.println ("You entered: " + firstnum + " and: " + secondnum);
}
else
System.out.println ("Your first number was not greater than your second number. Please try again.");
//while the frist number is greater, do this....
while (tempnum <= secondnum)
{
//if it's odd....
if (tempnum %2 == 1)
{
oddOutputMessage = (oddOutputMessage + tempnum + " ");
squaresum = (squaresum + tempnum * tempnum);
}
//otherwise it's even..
else
{
sum = sum + tempnum;
evenSumMessage = (evenSumMessage + sum + " ");
tempnum++;
}
}
// figures squares from 1 - 10
while (number <=10)
{
squarenum = (squarenum + number * number);
squareMessage = (squareMessage + number + " " + squarenum);
number++;
}
oddSquareMessage = oddSquareMessage + squaresum;
System.out.println (oddOutputMessage);
System.out.println (oddOutputMessage);
System.out.println (squareMessage);
System.out.println (evenSumMessage);
System.out.println (oddSquareMessage);
}
}
In your first loop, think hard about the conditions under which you increment tempnum. What happens when it's odd? Does tempnum get incremented?
There are a number of problems with your code. I'd rather you work through the problem yourself. You can use "println" debugging to print out the variables along the way if you don't know how to debug code.
Take the input 3 and 1 and walk through your program line by line and think about what the answer is going to be in your head (or on paper). See if that matches your expected results.
Here are some general comments about your code:
Consider breaking the different output into different subroutines: dumpOddNumbers(low, high), sumEvenNumbers(low, high), ...
Try to limit a variables scope as much as possible. Don't define the variables at the top and then use them later. Try to define them right before you need them. This will limit your unintended consequences. Try to not re-use variables unless it is temporary counters.
while (tempnum <= secondnum) These sort of lines should be for loops. One of the problems with the code is that if the first number is < then the second (the input 1 10 for example), the program loops forever because tempnum is not incremented if the number is odd.
while (tempnum <= secondnum) should probably be for (int tempnum = firstnum; tempnum <= secondnum; tempnum++)
while (number <= 10) should be for (int number = 1; number <= 10; number++)
You define the message at the top of your program but you shouldn't tack on results later. Do something like println(msgString + resultValue).
Take a look at StringBuilder() instead of msg = msg + ... type of logic. Much more efficient.
When you check the numbers are in the right order and spit out an error message, are you sure you want to continue? I think you should return there.
The following code does not match the comment. Which is correct?
// while the frist number is greater, do this
while (tempnum <= secondnum) {
Hope this helps.