Java while loops/ math logic - java

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.

Related

While loop will not continue to ask the user for an input

I am very new to java and I need help. Basically, I have a program that asks the user to input a number. When the number is input, it takes a sum of all of the odd numbers before that number and adds them up. What I'm trying (and failing) to do is, make another loop whereby, when the user is prompted to ask for a number to sum up the odd numbers, I want to make it so that it will only continue when an odd number is entered, otherwise it will keep repeatedly asking the user until they enter an odd number. I know that using a while loop will solve this issue, but I'm not sure how to get it to work.
Here's my code:
import java.util.Scanner;
public class OddCalculator {
private static Scanner sc;
public static void main(String[] args)
{
int number, i, oddSum = 0;
sc = new Scanner(System.in);
System.out.print(" Please Enter any Number : ");
number = sc.nextInt();
while (number % 2 !=0) //HERE IS WHERE IM HAVING THE ISSUE
{
continue;
}
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\n The Sum of Odd Numbers upto " + number + " = " + oddSum);
}
}
Thanks in advance!
continue; as a statement scans 'upwards and outwards' for the first construct that can be continued. Things that can be continued are currently only for, while and do/while statements, so it finds while (number % 2 != 0) and will continue it.
To continue a while loop means: Jump straight back to the condition number %2 != 0, evaluate it, and then enter the loop again if it is true, or hop to the } if it is false.
So, your code checks if the number is odd. If it is, it will .. continue. So, it will.. check if the number is odd. If it is, it will check if the number is odd. If it is, it will check if the number is odd.... forever.
Presumably your intent is to ask the user again, but then you'd have to wrap the loop around more code: Start with the print, because certainly sc.nextInt() needs to be inside the loop. That does mean you won't have a number value to check, but that's what do/while loops are for: To guarantee you loop at least once (and so that you can use anything calculated in the loop as part of the condition).
You should also use the scanner inside the while loop in case the number is not odd.
while (number % 2 !=0) {
number = sc.nextInt(); // Use here as well to keep asking for a number until is odd
}
Your confusion seems to be coming from misunderstanding that continue means going back to the while loop, and break is what gets you out of the loop. Does this work for you?
System.out.println(" Please Enter any Number : ");
number = sc.nextInt();
// keep asking for a number for as long as it is even (condition is false on odd)
while (number % 2 == 0) {
System.out.println("Please enter another number: ");
number = sc.nextInt();
}
System.out.println(number + " is now odd!");
I hope this output is what you are looking for, the reason why your previous code doesn't work is that number = sc.nextInt(); is the reason why you can prompt the user for an input, so you have to loop it, furthermore, you can give a specific prompt base on what the user has inputted in the if statement, hope this helps!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// int number, i, oddSum = 0;
int number, i, oddSum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter any Number : ");
do{
number = sc.nextInt();
if(number % 2 == 0){
System.out.print("Please Enter an odd number!: ");
}
}while(number % 2 == 0);
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\nThe Sum of Odd Numbers up to " + number + " = " + oddSum);
}
}
Output:
Please Enter any Number : 2
Please Enter an odd number!: 2
Please Enter an odd number!: 3
The Sum of Odd Numbers up to 3 = 4

Converting a string of numbers from Scanner to integers using loop?

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.

Java - Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits

I have seen this question asked a few times, but all of the responses have included functionality that I haven't learned yet in this class and am I sure there must be a way to do it with only what I have learned. No arrays, etc... just loops and prior. I am not really looking for the answer, but just some direction. I have included the code I have already done. The program needs to be able to hand negative numbers, the sum and then print in the proper order. Right now my code does everything except print in the proper order. I understand why it is printing in reverse order (because the loop gets rid of and then prints the last number in the int), but I can't seem to figure out a way to change it. I have tried converting it to a string, char and just can't get it. Please take a look, and provide some guidance if you don't mind. thank you in advance.
public static void main(String[] args) {
int num;
int sum;
int temp;
System.out.print("Enter an integer, positive or negative: ");
num = keyboard.nextInt();
System.out.println();
if (num < 0)
num = -num;
sum = 0;
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
System.out.print(temp % 10 + " ");
}
System.out.println(" and the sum is " + sum);
}
}
Not knowing what they've taught you in class so far, an easy albeit inefficient thing to do is to recreate the number as string.
String numbers = "";
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
// System.out.print(temp % 10 + " ");
numbers = (temp % 10) + " " + numbers;
}
System.out.println(numbers + "and the sum is " + sum);
You were already grabbing the ones digit with (temp % 10) and then right shifting the original number with num = num / 10. There are other data structures you could use like a Stack or a LinkedList that are more natural to use in a situation like yours, or you could use a StringBuilder to append the digits to the end and then use the reverse() method to get them back in the correct order, but those data structures probably come after Arrays which you mentioned you didn't know.
Given those constraints, I used String concatenation. In general here is what happens:
String numbers = "";
num = 123;
digit = num % 10; // digit=3
num /= 10; // num=12
numbers = digit + " " + numbers; // numbers="3 " uses old value on right side of the equals
// next iteration
digit = num % 10; // digit=2
num /= 10; // num=1
numbers = digit + " " + numbers; // numbers="2 3 " see how the digit is put to the left of the old value
// last iteration
digit = num % 10; // digit=1
num /= 10; // num=0
numbers = digit + " " +numbers; // numbers="1 2 3 " notice there is an extra space at the end which is ok for your example
Set a counter, loop num/10, if result>0 counter++. In the end, counter+1 will be the number of digits
System.out.println("Please enter numbers: ");
int number_entered = input.nextInt();
int sum = 0;
String reserve = "";
if (number_entered < 0 ) {
number_entered = number_entered * -1;
}
for (number_entered = number_entered; number_entered > 0; number_entered/=10){
int lastdgt = number_entered%10;
sum += lastdgt;
reserve = lastdgt + " " + reserve + " ";
}
System.out.println(reserve);
System.out.println("The sum is = " + sum );
}
}

Java sum of numbers error

This code seems to run well, but am getting error message regarding calculating the sum of the integers entered.
The point of the exercise is to input a series of numbers, and after the value -1 is entered, calculate the sum of the numbers, how many numbers were entered, the mean value, and the number of odd and even numbers.
The output I get suggests the program is running fine, but still get an eror message.
With input 1 17 2 18 17 -1 should print "sum: 55" expected:<55> but was: <0>
Apologies in advance if my Java syntax is a bit inelegant. I'm fairly new at this! Code below.
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type numbers: ");
int n;
double sum = 0.0;
int i = 0;
double average = 0.0;
int odd = 0;
int even = 0;
while (true) {
n = Integer.parseInt(reader.nextLine());
if (n != -1) {
System.out.print("Type numbers: ");
sum += n;
i++;
average = sum / i;
if (n % 2 == 0) {
even++;
} else {
odd++;
}
} else {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + i);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
You're printing 55.0. It seems you're getting this program tested by another program which you don't have access to the source code of.
Issue 1
You probably want to print 55 specifically.
Instead of:
double sum = 0.0;
Do:
int sum = 0;
Issue 2
Use int over double. Cast to double for the average value.
Then instead of this:
average = sum / i;
Do something like:
average = (double)sum / i;
Issue 3
Also, it seems the error message wants you to print as sum: 55.
So change this:
System.out.println("The sum is " + sum);
To:
System.out.println("sum: " + sum);

Four Numbers Program: Grouping numbers

I created a program that enables you to type in four numbers that must have specific requirements:
-must be a multiple of 4 or 6
-if greater than 500, must be a multiple of 10
The program takes the four numbers and gives you the sum of them, the average of them, shows you the smallest of the four numbers and finally the largest of the four numbers.
Now I want to try and display a group that each number belong to. I want these groups if you were wondering:
Group Tens if the number is between 0 and 99
Group Hundreds if the number is between 100 and 999
Group Thousands if the number is between 1000 and 999,999
Group Others if the number is greater than 999,999
My problem is I do not know where I should being placing them into my program (below)
import java.util.Scanner;
public class FourNumbersProgram {
private static int readNumber(String message, Scanner in) {
System.out.println("Enter a numbers divislbe by 4 or 6. No negatives.");
System.out.println("**If greater than 500: must be multiple of 10");
System.out.print(message);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, couldn't understand you!");
System.out.print(message);
}
int a = in.nextInt();
return a;
}
private static int readNumberToMatchCondition(String message, Scanner in) {
int number = 0;
do {
number = readNumber(message, in);
if (number < 500) {
if (number % 4 != 0 && number % 6 != 0) {
System.out.println(number + " not divisible by 4 or 6");
} else {
return number;
}
} else {
if (number % 4 != 0 && number % 6 != 0) {
System.out.println(number + " not divisible by 4 or 6");
} else if (number % 10 != 0) {
System.out.println(number + " is greater than 500 and not divisible by 10");
} else {
return number;
}
}
} while (true);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int randomNumber1 = readNumberToMatchCondition("Enter first number:", in);
int randomNumber2 = readNumberToMatchCondition("Enter second number:", in);
int randomNumber3 = readNumberToMatchCondition("Enter third number:", in);
int randomNumber4 = readNumberToMatchCondition("Enter fourth number:", in);
int sum; // sum of number1, number2, number3, and number4
int avg; // average of number1, number2, number3, and number4
int largest; // largest number of the four integers
int smallest; // smallest number of the four integers
sum = (randomNumber1 + randomNumber2 + randomNumber3 + randomNumber4);
avg = ((sum) / 4);
smallest = randomNumber1;
smallest = (randomNumber2 < smallest) ? randomNumber2 : smallest;
smallest = (randomNumber3 < smallest) ? randomNumber3 : smallest;
smallest = (randomNumber4 < smallest) ? randomNumber3 : smallest;
largest = randomNumber1;
largest = (randomNumber2 > largest) ? randomNumber2 :largest;
largest = (randomNumber3 > largest) ? randomNumber3 :largest;
largest = (randomNumber4 > largest) ? randomNumber4 :largest;
System.out.println();
System.out.println("First number entered: " + randomNumber1); //prints first number entered
System.out.println("Second number entered: " + randomNumber2); //prints second number entered
System.out.println("Third number entered: " + randomNumber3); //prints third number entered
System.out.println("Fourth number entered: " + randomNumber4); //prints fourth number entered
System.out.println();
System.out.println("The sum is: " + sum); //prints sum of four numbers
System.out.println("The average is: " + avg); //prints average of four numbers
System.out.println("The smallest number is: " + smallest); //prints smallest of the four numbers
System.out.println("The largest number is: " + largest); //prints largest of the four numbers
System.out.println();
}
}
Here is a transcript of my code:
my professor gave me this sample of a grouping program (below)
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);// read a number
System.out.println("Enter a number: ");
int number = in.nextInt();
if (number < 0) {
System.out.println("Error: Sorry, no negative numbers allowed.");
System.exit(0);
}
int grp1 = (number / 100) + 1;
int grp2 = (number / 1000) + 1;
int grp3 = (number / 1000000) + 1;
switch (grp1){
case 1: // Group Tens
System.out.println(number + " belongs to Group Tens");
break;
default:
switch (grp2) {
case 1:// Group Hundreds
System.out.println(number + " belongs to Group Hundreds");
break;
default:
switch (grp3) {
case 1:// Group Thousands
System.out.println(number + " belongs to Group Thousands");
break;
default:// Group Others
System.out.println(number + " belongs to Group Others");
}
}
}
in.close();
}
}
Heres a transcript of his code:
I know his program is asking for the user to type in one number and the program groups it. I was wondering how to put something like this into my program. I am confused because I have four numbers that have to be grouped and I'm not sure if I have to repeat something similar to my professors program for all of my four numbers (randomNumber1, randomNumber2, randomNumber3, randomNumber4
Please no positing an entire corrected code! I want to fix it myself and learn!
Your professors program will work for all of your numbers. All you need to do is call the method 4 times. Once for each number. What you need to do is put his code into a method on it's own. (Remember, if he's given it to you as a guide, then he will probably want you to give a go at writing the logic yourself).
Let's say you put his code in a method that looks like:
public void displayNumberGroup(int number)
{
// Displays number group using your prof's code.
}
Then, next, all you need to do is pass each value that you've loaded, into that method. For example: displayNumberGroup(randomNumber1);. This will calculate the grouping for that number. I'll leave it up to you to put this stuff into context, since you've requested to not be spoonfed the answer (which is very commendable!).
Instead of doing randomNumber1, randomNumber2, ect you can make them into an array. By doing that, you can then put a for loop over the given switch and run it 4 times so all of your numbers have groups. If you need me to explain any part of this with a simple example I will, but I know you want to do most of this yourself so if you have any questions let me know.

Categories

Resources