I am working on a Java 1.8 script in which I am trying to set a user input number range, in which user can only enter number between 0 and 1000. I am trying to set the range using the below code, but it is still allowing me (the user) to enter number greater than 1000.
} while (0 < digit && digit < 1000);
I tried searching for similar questions here, but a lot of answers I find basically recommend doing what I am doing below, and that seems to work for other users, so I don't understand why it is not working for me.
The code above is not throwing any errors, so I am baffled as to why it is still allowing me to enter number bigger than 1000. I am a Java novice so possibly some logic error...
This is my full code below. The purpose of the script is to enter number between 0 and 1000 and have the system calculate the sum of its digits. It is successfully calculating the sum, but when I enter a number greater than 1000, the sum is zero...
System.out.println("Enter a number between 0 and 1000.");
int num = 4567;
int sum = 0;
while (num > 0 && num <1000) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println("The sum of the digits is " + sum);
To take user input, requiring it to be in the range of 1..999, you'll need something like this:
do {
num = // get the input
} while (num < 1 || num > 999);
Your second loop is completely skipped if the number is 1000 or greater -- the sum will be the initial 0 for any such values. Maybe the second condition is not necessary at all -- it should work just fine for numbers of any size:
while (num > 0) {
sum += num % 10;
num /= 10;
}
Related
I tried to write a method (for kicks) that would sum up the digits at even places using Java recursion.
For example, the number 23495 would return 3+9 = 12.
I am unsuccessful and would appreciate hints or what I'm doing wrong.
int sumEven = 0;
int sumOdd = 0;
int i = 1;
if (n == 0)
return sumEven;
if (n != 0) {
if (i % 2 == 0)
{
i++;
sumEven += n % 10;
}
else
{
i++;
sumOdd += n % 10;
}
}
return sumEven + getEven (n/=10);
The problem is you're trying to do too much - take a look at my comment on the Q
A recursive method needs an input that contains everything it needs to work with, a return value, and an execution path where it calls itself until something happens that means it doesn't need to call itself any more - without this bit it will recourse until it overflows the stack
int sumEveryOtherDigit(int input){
if(input >= 100)
return input%10 + sumEveryOtherDigit(input/100);
else
return input%10;
}
This takes the input , and if there is any point to running again (if the input is at least 100) takes the rightmost digit plus running itself again with a smaller number
Eventually the number gets so small that there isn't any point running itself again so it just returns without running itself again and that is how the recursion stops
Now from your comment on another answer it seems you want to determine even and odd as working from the left so we need to either start with the number (1630) or the number divided by ten (23495 -> 2349) - basically to start the recursion going we always want to pass in a number with an even number of digits
int num = 23495;
int numOfDigits = (int)Math.log10(num)+ 1;
if(numOfDigits%2==0)
result = sumEveryOtherDigit(num);
else
result = sumEveryOtherDigit(num/10);
You should iterate over the digits of the input number, and then sum the remainder mod 10 only for even position digits:
int input = 23495;
input /= 10;
int sum = 0;
while (input > 0) {
sum += input % 10; // add last even digit
input /= 100; // advance by two digits, to the next even digit
}
System.out.println("sum of even digits of input is: " + sum);
This prints:
sum of even digits of input is: 12
The project is to create a program that takes input from the user in JOption Pane and checks if a number is prime or not. The program is supposed to loop until the user enters 0, which triggers the program to calculate max, min, sum, count, and average.
Ive completed 99% of the assignment, except the first number that I enter does not get printed out like the others but it still gets included in calculations
import javax.swing.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// Main Method
userInput();
}
public static void userInput() {
int number;
int sum;
int count; // declaring variables
int max= 0;
int min= 1;
float average;
String userNumber; // Number typed by user
sum = 0; // start at 0 for sum
count = 0; // start at 0 for counter
// prompt user to enter a positive number
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
// convert to int
number = Integer.parseInt(userNumber);
// if the number entered is positive and not 0, the loop repeats
while ( number != 0 && number > 0) {
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
// checking if number entered is prime or not
int i,m=0,flag=0;
m=number/2;
if(number==0||number==1){
System.out.println(number+" is not a prime number");
}else{
for(i=2;i<=m;i++){
if(number%i==0){
System.out.println(number+" is not a prime number");
flag=1;
break;
}
}
if(flag==0){ System.out.println(number+" is a prime number"); }
}
}
if ( count != 0 ) {
// as long as one number is entered, calculations are done below
// calculate average of all numbers entered
average = (float) sum / count;
// printing out the results
System.out.printf("The average is : %.3f\n", average);
System.out.println("The sum is : "+sum);
System.out.println("The count is : "+count);
System.out.println("The max is : "+max);
System.out.println("The min is : "+min);
}
}
}
i need the first entry to print like the rest, please help me find where to put in the loop
Can you explain more what you need? What input do you give it and what output do you see?
I noticed that you're adding numbers before the call to JOptionPane, is it possible that you have count larger by one than your actual count of numbers? Your indentation is terrible, you should clean it up, I'm having trouble reading the code period.
// 1 START OF LOOP
while ( number != 0 && number > 0) {
// 2 ADD NUMBER TO SUM
sum += number;
// starting count and sum at 0
count++;
// repeating user input prompt unless 0 is entered
// storing values for min and max as we go
if (number > max)max=number;
if (number < min & number != 0)min=number;
// 3 THEN GET INPUT. WHAT???
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
You have several issues in your program. The reason why the first number is never considered is that you have
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
two times in your code (before the while loop and in the while loop).
I would suggest to initialize number with Integer.MAX_VALUE: number = Integer.MAX_VALUE;
Then remove
userNumber = JOptionPane.showInputDialog("Enter a positive integer or 0 to quit");
number = Integer.parseInt( userNumber );
before the while loop.
There is a & missing in if (number < min & number != 0)min=number;
=>
if (number < min && number != 0) {
min=number;
}
The condition in the while loop can be simplified by writing while ( number > 0) { because > 0 means != 0 too.
I would also suggest to write your code a little better for readability. Always use curly braces for conditions (if), even when you only execute one line if the condition is true.
I hope this helps. Let me know if you need more help but you should be able to solve this assignment now on your own :)
I know this code is wrong. I'm a beginner so bear with me.
I need to find the lowest odd number but it keeps coming up as zero no matter what numbers are entered. I need to initialize 'lowest' but how/where do I initialize it?
lowest = 0 is causing a problem but I'm not sure where to initialize lowest
class Odd
{
public static void main(String[] args)
{
int number; //the number entered by the user
int input; //the amount of numbers to be entered by the user
int index;
int lowest = 0; //lowest odd number
System.out.println("How many numbers? ");
input = EasyIn.getInt();
for (index = 1; index <= input ; index ++)
{
System.out.println("Enter number " + index + ":" );
number = EasyIn.getInt();
if ((number % 2 == 1) && (number < lowest))
{
lowest = number;
}
}
System.out.println("The lowest odd number entered was " + lowest);
}
}
If you're sure your input isn't empty, a solution is to initialize lowest to a big enough value :
int lowest = Integer.MAX_VALUE;
This ways all values will be smaller, so lowest will be one of the values of your input.
You are starting at 0 so you will not get a value larger. If you start like this
int lowest = Integer.MAX_VALUE;
Also (n % 2) will only be 1 for positive numbers. If you want to test for odd negative numbers you want (n & 1) != 0
Note: Integer.MAX_VALUE is an odd number so even if this is the only value it will be the maximum. However, if you want to be able to tell the difference between some one entering this value and no odd values you can use this instead.
long lowest = Long.MAX_VALUE;
This will allow you to tell the difference between Integer.MAX_VALUE being entered and no value as Long.MAX_VALUE is much higher.
You initialise lowest as 0 and then look for numbers lower than it (and odd).
I'd initialise it as EasyIn.getInt() so it's the first number in your list to check through.
I am trying to find the even sum and even max from numbers inputted by the user. For example, if they answered "How many integers?" with 4 and inputted the integers: 2, 9, 18, 4 it should output:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 24
even max = 18
Here is my code:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
//prompt user to enter the first integer
System.out.print("next integer? ");
int firstNum = console.nextInt();
//set the even max to the firstNum
int evenMax = firstNum;
//set the evenSum to zero
int evenSum = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 2; i <= numbers; i++) {
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the first number is even
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
//check to see if the numbers entered are even
if (num % 2 == 0) {
//if they are even add them to the evenSum
evenSum += num;
}
//check to see if the number entered is bigger than the first number
if (num > firstNum) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
But here is what is my output is:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 28
even max = 4
Could someone help me figure out what the problem is?
You were doing some really weird stuff where the first time a number was entered it was treated as special. This was causing the first even number entered (2, in this case) to be added multiple times to the total.
Put all of your input in the same loop so you can treat everything equally:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
int evenSum = 0;
int evenMax = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 0; i < numbers; i++) {
//input new number
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the number is even. if it is not even,
//we don't care about it at all and just go to the next one
if (num % 2 == 0){
//add it to the sum
evenSum += num;
//if it's larger than the maximum, set the new maximum
if (num > evenMax) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
As you can see, this code also only checks to see if a number is even once. There is no need to be continuously checking if num is even every time you use it: its value is not changing during the duration of a single run of the loop.
Move the following code inside the for loop to just before the for loop-
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
This will prevent the repeated addition of the first number in the evenSum
You also want
if (num > evenMax) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
or, alternatively
if (num > evenMax && num % 2 == 0) {
evenMax = num;
}
In your scenario, firstNum is 2 so every number after it is technically larger, so you will (theoretically) not get the largest even number entered after the first number.
Either move the first if condition inside the for loop upwards (outside of the for loop)
or store all of the user inputs in a data structure i.e. Array before processing them.
Storing them in Array would make it easier to manipulate the data.
Working code:-
Scanner console = new Scanner(System.in);
int numbers =0, firstNum =0, num =0 ;
System.out.print("how many integers? ");
numbers = console.nextInt();
System.out.print("next integer? ");
firstNum = console.nextInt();
int evenMax = 0;
int evenSum = 0;
if(firstNum%2==0)
{
evenSum = firstNum;
evenMax = firstNum;
}
for (int i = 1; i < numbers; i++) {
System.out.print("next integer? ");
num = console.nextInt();
if (num % 2 == 0) {
//don't add firstNum multiple times to the evenSum, earlier it was added every time you entered an even number
evenSum += num;
//check if the number you entered, i.e. num greater than the already existing greatest number i.e. evenMax and if so update it
evenMax = num > evenMax: num?evenMax;
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
Hope this helps. There are three major problems in your code:-
The firstNum(if it's even) gets added to the sum every time you enter a even number. i.e. if first number is 4 and the loop runs 10 times and encounter 6 even numbers, then along with the even number 4 also gets added six times. If you want to use it as a special number and get it's value separately then you'll have to add it to the sum before the loop.
You should compare every new even number to the previous greatest even number and hence set the value of evenMax. You are comparing them to the firstNum so if the first number is 2 and the last even number is anything greater than two, it would be set as the value of evenMax. Compare every even number to the current maximum even number i.e current value of evenMax.
You don't check if the first number is evenor not and assign it to even max. So if it is 999999 it still get's assigned, but it is not even.
Please check it as correct answer and vote up if you find it useful.
The problem is :
Write a program that prompt the user to enter 5 numbers and find the
two largest values among them. If the user enters number more than 100
or less than – 100 the program should exit.
Hint: use break.
My code is :
import java.util.*;
public class q2 {
static Scanner scan = new Scanner (System.in);
public static void main (String[] args ) {
int num;
int max=0;//define Maximum value and save it in variable max = 0;
int secondMax=0;//define the second maximum value and save it in variable secondMax = 0;
System.out.println("Please , Enter 5 numbers between 100 and -100 "); //promet user to enter 5 numbers with the condition
for (int count=0 ; count<5 ; count++) // start loop with (for)
{
num = scan.nextInt();//user will enter number it will be repeated 5 times .
if( num > 100 || num<-100) //iv the user enter a number less than -100 or geater than 100 program will quit from loop
{
System.out.println("The number you have entered is less than -100 or greater than 100 ");//telling the user what he did
break;//End the loop if the condition ( num > 100 || num<-100) is true .
}
if(num>max )//Another condition to find the maximum number
max = num;//if so , num will be saved in (max)
if (num >= secondMax && num < max)// A condition to find the second Maximum number
secondMax = num;//And it will be saved in (secondMax)
}//End loop
System.out.println("The largest value is " + max); //Print the largest number
System.out.println("The second largest value is " + secondMax );//print the second largest number .
}//End main
}//End class
This is what my code outputs:
Please , Enter 5 numbers between 100 and -100
20
30
60
20
-10
The largest value is 60
The second largest value is 20
The second largest number is incorrect - 20, not 30. What did I do wrong?
There can be two cases,
You find new max, in this case, update secondmax and set this num as max
You find new SecondMax, update only secondmax
Try this
if(num>secondMax&&num<max) // case 2
{
secondMax = num
}
else if(num>max) // case 1
{
secondMax = max;
max = num;
}
if(num>max )//Another condition to find the maximum number
secondMax = max;
max = num;//if so , num will be saved in (max)
else if (num >= secondMax)// A condition to find the second Maximum number
secondMax = num;//And it will be saved in (secondMax)
If you replace the highest number by one that is even higher, the former largest one becomes the second largest (becaus it'S still larger than the former second largest). Your code doesn't reflect that.
Everytime you change the largest nubmer, set the second largest to the old largest one.
In the condition where the max number change first save previous max than assign new max otherwise second max should be adjusted if it less than the number.
if(num>max ){//Another condition to find the maximum number
secondmax = max;
max = num;//if so , num will be saved in (max)
} else if (num > secondmax) {
secondmax = num;
}