I've been working on the Blue Pelican Java project called Add 'Em Up for several hours now, and I can't figure out how to get it to work. The project description is this:
Consider the following program that allows something like 8 + 33 + 1,345 +137 to be entered as
String input from the keyboard. A Scanner object then uses the plus signs (and any adjoining
whitespace) as delimiters and produces the sum of these numbers(1523).
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1,345 +137 : ");
String s = kb.nextLine( );
Scanner sc = new Scanner(s);
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}
The output will typically look like this:
Enter something like 8 + 33 + 1,345 +137 : 8 + 33 + 1,345 + 137
Sum is: 1523
Now modify this program so as to allow either plus or minus signs. Don’t forget to allow for a
leading plus or minus sign on the first number in the sequence. If the leading number has no sign,
assume the number is positive. Your output should typically appear as follows:
Enter something like 8 + 33 + 1,345 -137 : 8 + 33+ 1,345 -137
Sum is: 1249
The code below is what I currently have. The program works just fine for adding numbers, but for some reason the subtraction isn't working. For example, if you enter 5-2, the answer comes out as -7 instead of 3.
public class AddEmUp {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
int sum = 0;
if (s.contains("+")) {
sc.useDelimiter("\\s*\\+\\s*");
while (sc.hasNextInt()) {
sum = sum + sc.nextInt();
}
}
if (s.contains("-")) {
sc.useDelimiter("\\s*\\-\\s*");
while (sc.hasNextInt()) {
sum = sum - sc.nextInt();
}
}
System.out.println("Sum is: " + sum);
}
Any help on what I should be trying to do in order to fix this would be much appreciated. Thanks!
The subtraction case is going to require a little more work than addition in this code! I think once you understand what is happening, you'll see how you need to adjust your strategy.
This is what is happening right now with the input 5 - 2.
int sum = 0
s.contains("-") is true.
sum = sum - sc.nextInt() occurs,
Remember at the top of your code sum was set to zero!
so sum = 0 - 5
Now sum = -5.
s.contains("-") is true.
sum = sum - sc.nextInt() occurs
sum = -5 - 2.
At the end of your program, sum = -7.
You are going to need to restructure the logic of your program a bit. Right now, the first thing you check is to see if there is either a '+' or a '-' symbol in your input. If there is a '+' symbol, you start from sum=0 and add every number you see. This works pretty well for addition, and you'll always get the right answer. If there is a '-' symbol, you start from sum=0 and subtract every number you see. That's not quite the intention with subtraction though. In the case of 5 - 2, what you would rather do is from sum=0 '+ 5' and then '- 3'.
Your code is fine in the sense that it compiles and runs - what you have here is what is known as a 'logic bug'. The steps that you have asked the program to do are not the same as the actual steps you want it to do. Give careful thought to what is happening at each point of your program to make sure that it behaves correctly.
Related
I am making a program that accepts user input to subtract all the numbers desired by the user
I first made the program ask how many numbers the user wants to subtract, and initialized the value in int inputNum, which is then passed on to the for loop for (int Count=1; Count<=inputNum; Count++), so that the program loops for user input, based on the inputNum.
Unfortunately, the output is wrong. I can't understand how this would work properly.
I've tried switching the operator in difference by making difference =- toBeSubtracted; into difference -= toBeSubtracted;
For difference =- toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -5
For difference -= toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -15
Here is the code:
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
int toBeSubtracted = scan.nextInt();
difference =- toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
Ok this might help you out:
difference = 0
and than you have:
difference -= toBesubtracted
so what you are doing is:
difference = difference - toBeSubtracted
which in terms is
difference = 0 - 10
difference = -10 - 5
thus you get -15
and where you have
difference =- toBeSubtracted
it is the same as
difference = -1 * toBeSubtracted
thus you get -5
I suppose you want output of 5. Here is your code with one change
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = scan.nextInt(); // so read in the first number here.
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1;Count<inputNum; Count++) // go till from 1 to inputNum - 1 because you have already got one number above
{
int toBeSubtracted = scan.nextInt();
difference -= toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
You need to understand the operator shorthand notation. You should write -= for minus shorthand. The shorthand is equal to difference =difference - tobesubstracted. Since your initial value is 0 it becomes 0-10-5= -15.
Assign the first value as difference and then do the substraction of next values.
So something like:
difference = scanner.nextInt();
And then do the loop for rest of the values to minus from initial value.
The problem isn’t that your program is working incorrectly.
The problem is that the requirements are nonsense. You can have the difference between two numbers. The difference between 19 and 8 is 11. There is no such thing as the difference between 3 or more numbers. Therefore no program could ever produce that.
That said, Davis Herring is correct in the comment: there is no =- operator. You tried to use one in the line:
difference =- toBeSubtracted;
But the line is understood as just:
difference = -toBeSubtracted;
So your program just outputs the negative of the last entered number. I tried entering three numbers, 11, 3 and 5. The first time through the loop difference is set to -11. Next time this value is overwritten and -3 is set instead. In the final iteration the difference is set to -5, which “wins” and is output.
Instead I suggest that your program should always subtract 2 numbers, as you are also trying in your example. So the user needs not enter the number of numbers, but is just told to enter the two numbers. Then you also don’t need any loop. Just read the first number, read the second number, subtract the second from the first (or the first from the second, or the smaller from the larger, what you want) and print the result. I am leaving the coding to you to avoid spoiling it.
I did this
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
int currentNumber = 0; //current number from scanner
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
if(Count == 1)
{
//nothing to subtract if count is 1
currentNumber = scan.nextInt();
difference = currentNumber;
}
else {
currentNumber = scan.nextInt();
difference = difference - currentNumber;
}
}
System.out.println("The difference of those numbers is " + difference);
}
}
You started your difference at 0. So if you subtracted two numbers, 15 and 3, then you would get 0 - 15 - 3 = -18. I set the difference equal to the first number, 15 in the first loop. Then it should work correctly because you do 15 - 3 = 12.
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.
I am having trouble printing out the sum of a palindrome without using ant string methods and only using mathematical methods. I have figured out how to calculate the sum and everything but when I try to print out the sum it gives me a list of all of the numbers. For example, for the number 11, the output is this
1
3
6
10
15
21
28
36
45
55
66
I want to figure out how to only print out the last number, 66, which is the sum of the numbers 1 to 11 and also how to make the program print out "1 to 11" since the numbers are user inputted using the scanner method. Below my code I have included what my output should look like. Thank you so much!
import java.util.Scanner;
public class Palindrome {
public static void main (String args []) {
System.out.println("Please enter an integer > 0:");
Scanner keyboard=new Scanner(System.in);
int palindrome=keyboard.nextInt();
int palindrome1=palindrome;
int num;
int sum;
int rev=0;
if (palindrome<=0) {
System.out.println("Sorry, you must enter an integer greater than zero.");
}
while (palindrome!=0) {
rev=rev*10 + palindrome % 10;
palindrome/=10;
System.out.println("the integer "+palindrome1+ " is a palindrome");
}
if (palindrome1==rev) {
System.out.println("palindrome");
} else {
System.out.println("not");
}
num=1;
sum=0;
while (num<=palindrome1) {
sum=sum+num;
num++;
System.out.println(sum);
}
}
}
The output should look like this:
Please enter an integer > 0: 11
The integer 11 is a palindrome.
The sum of the numbers from 1 to 11 is 66
You could always use the common math rule which describes the sum of a number from 0 to n:
This is also simpler as you don't have to really worry about accumulating the values in a loop.
In your scenario, all you'd need to do in order to print the value out would be to compute this.
Reduced, it'd be:
System.out.println((n*n) - n))/2);
Alternatively, if you only want to print the last item that you're adding, then only print after the loop has completed.
A few suggestions:
You may simplify the sum of consecutive integers using the rule stated above by Makoto.
Naming your integer variable 'palindrome' before confirming that it is a palindrome may be confusing.
The statement on line 24 appears to be incorrectly placed.
You have indicated that you don't want the sum to be printed each loop iteration, so you might want to move the last println outside that while loop.
Change the last while loop to this:
while (num<=palindrome1){
sum=sum+num;
System.out.println(num);
num++;
}
System.out.println(sum);
}
I'm trying to make a program to analyze data, but the amount of data changes each time. Here is an example output:
Please enter the sample size: 3
Enter numbers for Trial 0
Enter sample #0:50
Enter sample #1:49
Enter sample #2:51
Enter numbers for Trial 1
Enter sample #0:30
Enter sample #1:31
Enter sample #2:32
Enter numbers for Trial 2
Enter sample #0:25
Enter sample #1:26
Enter sample #2:27
Enter numbers for Trial 3
Enter sample #0:15
Enter sample #1:16
Enter sample #2:17
Sample # Trial 1 Trial 2 Trial 3 Trial 4
0 50 30 25 15
1 49 31 26 16
2 51 32 27 17
-------------------------------------------------------
Average: 50 31 26 16
Min Average: 16
Max Average: 50
The trials do NOT concur!
This is the code I have currently:
import java.util.Scanner;
public class DataAnalyze {
public static void main(String[] args) {
int sample = 0;
int avg;
int t1 = 0;
int t2;
int t3;
int t4;
int val;
int max;
int min;
Scanner input = new Scanner(System. in );
System.out.println("Please enter the sample size: ");
sample = input.nextInt();
System.out.println("Enter the numbers for Trial 0");
for (int i = 0; i < sample; i++) {
System.out.println("Enter sample # " + i + " : ");
t1 = input.nextInt();
}
System.out.println("\tSample #\tTrial 1\tTrial 2\tTrial 3\tTrial 4");
System.out.println("\t" + (sample - 1) + "\t" + t1);
}
}
I guess what I'm asking is how to make the for loop collect the input for t1 the first time around, t2 the second time around, and t3 the third time around, etc. Basically, how do I change what input a value is being assigned to each time the loop iterates? I assume that some sort of array is the best way, but I'm not well versed in java so if you could provide me an example that would be great, thanks.
I think you mean to say generate unique random number when you say
make the for loop print out a different variable each time it iterates
This you can achieve by first adding ranges in list and then using shuffle() method of Collections class to get unique number.
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<11; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<3; i++) {
System.out.println(list.get(i));
}
In Java you can store an arbitrary number of objects in List classes. The generic ArrayList class would probably be suited to your needs. You would append numbers onto the list as you read them in.
You can replace the for loop with a while loop and check for end-ofinput by e.g. reading in as a string then first checking for an empty string ( user just hit return ) and if not convert the string to an int.
I don't know how to make the for loop print out a different variable
each time it iterates
I do no understand what you mean here. Do you mean print t1 on the first pass, then t2, then t3 and so on ? There's no simple way to do that and you would need to e.g. store those t-variables in an array and use an index calculated from your loop variable's value to do it, for example :
int t[4] ;
int i = 0 ;
while( .. )
{
System.out.println( "var = " + t[ i % t.length ] ) ;
i++ ;
};
Basically, I'm trying to write a program that converts a number from base 2 to base 10. What I tried doing was translating the process listed on this website under the "Doubling method" into a for loop, but for some reason the numbers I'm getting are way to big.
The basic formula is (2 * previousTotal) + (currentDigit of the ArrayList that holds the user's inputted binary number) = previousTotal.
So for 1011001 in binary, the math would be:
(0 x 2) + 1 = 1
(1 x 2) + 0 = 2
(2 x 2) + 1 = 5
(5 x 2) + 1 = 11
(11x 2) + 0 = 22
(22 x 2) + 0 = 44
(44 x 2) + 1 = 89
The console however, prints out 6185 as the result. I'm thinking it might have something to do with me using an ArrayList of characters, but the charWhole.size() returns 7, which is how many digits are in the user's binary number. As soon as I do charsWhole.get(w); however, I start getting big numbers such as 49. I'd really appreciate some help!
I wrote out this loop, and according to some print statements that I placed throughout the code and my variable addThis seems to be where the problem is. The console prints out a final total of 6185, when 1011001 in base 10 is actually 89.
public static void backto2(){
System.out.println("What base are you coming from?");
Scanner backToB10 = new Scanner(System.in);
int bringMeBack = backToB10.nextInt();
//whole
System.out.println("Please enter the whole number part of your number.");
Scanner eachDigit = new Scanner(System.in);
String theirNumber = eachDigit.nextLine();
String str = theirNumber;
ArrayList<Character> charsWhole = new ArrayList<Character>();
for (char testt : str.toCharArray()) {
charsWhole.add(testt);
}
System.out.println(theirNumber); // User's number
System.out.println(charsWhole); // User's number separated into elements of an ArrayList
System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.
int previousTotal = 0, addThis = 0, q =0;
for( int w = 0; w < charsWhole.size(); w ++) {
addThis = charsWhole.get(w); //current digit of arraylist PROBLEM
q = previousTotal *2;
previousTotal = q + addThis; // previous total gets updated
System.out.println(q);
System.out.println(addThis);
System.out.println(q + " and " + addThis + "equals " + previousTotal);
}
System.out.println(previousTotal);
You are attempting to add a character to an integer. The implicit conversion uses the ASCII value of the character, so that '1' gets converted to 49, not 1, because 49 is the code for the character '1'. Subtract '0' to get the actual integer value.
addThis = charsWhole.get(w) - '0';
This works because the digits 0-9 are represented in ASCII as the codes 48-57, so in effect you will, for '1', subtract 49 - 48 to get 1.
You'll still have to handle cases when the character is outside the range of allowable characters.
EDIT
Java uses Unicode, but for the purposes of the codes for the digits 0-9, the codes are the same (48 thru 57, or 0x30 thru 0x39) in both ASCII and Unicode.
The problem is that you're using the chars rather than the number value they represent. In the line
addThis = charsWhole.get(w);
the value of addThis is the ascii value of the character. For '0', this is 48. Use this instead:
addThis = Integer.parseInt(charsWhole.get(w));
Another suggestion to solve the same problem:
addThis = charsWhole.getNumericValue(w);
See here for more information.