How do i exclude negative numbers in an if loop? - java

For my project, the user enters a set of numbers, and some calculations are performed to give the desired output. One of the calculations is the find the sum of the odd numbers that are inputted. Looking at the given test cases, I noticed my code was adding the negative odd numbers, while the correct test cases do not. Is there any easy fix for this?
Thanks
Here is some of the code, what I have written minus a few parts.
import java.util.Scanner;
public class Test
{
public static void main (String[] args)
{
int min_interger = 0;
int sum_of_pos = 0;
int sum_of_odd = 0;
int count_of_pos = 0;
int userInput;
Scanner consoleInput = new Scanner(System.in);
do {userInput = consoleInput.nextInt();
if(userInput % 2 != 0)
{
sum_of_odd = sum_of_odd + userInput;
}
while (userInput != 0);
System.out.print("The sum of the odd integers is " + sum_of_odd + "\n")
}
}

Make sure to add odd and greater than zero numbers
if(userInput % 2 != 0 && userInput > 0)
{
sum_of_odd = sum_of_odd + userInput;
}

Related

How to find max number and occurrences

So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .
my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.
But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .
package myjavaprojects2;
import java.util.*;
public class Max_number_count {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int count = 0;
int max = 1;
System.out.print("Enter a Integer:");
int userInput = input.nextInt();
while ( userInput != 0) {
if (userInput > max) {
int temp = userInput;
userInput = max;
max = temp;
} else if (userInput == max) {
count++ ;
}
System.out.println("The max number is " + max );
System.out.println("The count is " + count );
}
}
}
So how do you take multiple inputs from the user on the same line .
You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.
int userInput = input.nextInt();
while ( userInput != 0) {
//all above logic
userInput = input.nextInt();
}
The code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0, count = 0, num;
System.out.println("Enter numbers:-");
while ((num = sc.nextInt()) != 0) {
if (num > max) {
max = num;
count = 1;
} else if (num == max) {
count++;
}
}
System.out.println("\nCount of maximum number = "+count);
}
}
And you don't have to use ArrayList or Array. Just keep inputting numbers till you get 0.
You can implement this with a single loop. The traditional concise pattern for doing so involves the fact that assignment resolved to the value assigned. Thus your loop can use (x = input.nextInt()) != 0 to terminate (handling exceptions, and non-integer input left as an exercise for the reader). Remember to display the max and count after the loop and reset the count to 1 when you find a new max. Also, I would default max to Integer.MIN_VALUE (not 1). That leaves the code looking something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Integer:");
int count = 0, max = Integer.MIN_VALUE, userInput;
while ((userInput = input.nextInt()) != 0) {
if (userInput > max) {
max = userInput;
count = 1;
} else if (userInput == max) {
count++;
}
}
System.out.println("The max number is " + max);
System.out.println("The count is " + count);
}

String of only even numbers and only odd numbers

I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input

How do you check if inputted array values are the same?

My program is supposed to make sure each value the user enters is between 10-100. The value is then stored in the array. That part works fine. The other condition is that the value the user enters has to be different from all the other arrays. ie...array[0]=20 so all of the other arrays can no longer equal to be set to 20. I've been trying to solve this but I'm just not sure where to go. I tried setting statements after my while(userInput < 10 || userInput > 100) to check for any repeats and that worked. The problem was then the user could enter values less than 10 and greater than 100. Any help would be greatly appreciated!
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
for(int x = 0; x < array.length; x++)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
while(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100: ");
userInput = input.nextInt();
}
array[x] = userInput;
System.out.println(array[x]);
counter++;
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
}
You should get rid of the for and second while loop, and check if the value entered is in the desired range.
If it is, you verify for duplicates, store it in the array and increment the counter. If it’s not, you show the bad input message.
Either way, it continues to ask for an valid input until the counter gets to 5.
I hope it helps!
I changed your logic a little bit, see if you can understand it
(There are better ways of doing this, but I think this is more understandable)
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
if(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100.\n");
}
else {
//This is a valid input, now we have to check whether it is a duplicate
boolean isItDuplicate = false;
for(int i = 0; i < counter; i++)
{
if(userInput == array[i])
{
isItDuplicate = true;
}
}
if(isItDuplicate == true)
{
System.out.print("Please enter a number that is not a duplicate.\n");
}
else
{
array[counter] = userInput;
System.out.println(array[counter]);
counter++;
}
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
Don't use variable counter when var x does the same thing for you.
Don't use nested loops when the limiting condition of both loops need to be checked together in each iteration. Merge those loops into one wherever possible.
First of all, get rid of your nested loops. They're redundant. Let's look at your problem's specification. Your input needs to fulfill 3 requirements:
Be greater than or equal to 10
Be less than or equal to 100
Be a unique element inside the array
The first two conditions are simple enough to check. For the final condition, you need to search the values inside the array and see if there are any matches to your input. If so, the input is invalid. A simple way to approach this is to check every member of the array and to stop if a duplicate is found. There are better, more efficient ways to do this. Don't be afraid to search the internet to learn a searching algorithm. Below is a simple solution to your problem. It's far from ideal or efficient, but it's easy enough for a beginner to understand.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
int userInput;
while(counter < 5) {
System.out.print("Enter a number between 10 & 100: ");
userInput = in.nextInt();
if( (userInput >= 10 && userInput <= 100) && !searchDuplicates(array, userInput) ) {
array[counter] = userInput;
counter++;
} else {
System.out.println("Invalid value entered");
}
}
for(int i = 0; i < array.length; i++)
System.out.println("Value " + (i + 1) + ": " + array[i]);
}
private static boolean searchDuplicates(int[] array, int input) {
for(int i = 0; i < array.length; i++)
if(array[i] == input)
return true;
return false;
}
}

Count How many number multiple by the number from input user between a range

again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot
write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.
Here my code
import java.util.*;
public class Exam3
{
public static void main(String args[])
{
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while(input < 100 || input > 200)
{
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count ++;
}
System.out.println("count is: " + count);
}
public static void int getCount(int input, int count)
{
for(int i = 499;i <= 1000; i++ )
{
if(i % input==0)
{
count++;
}
}
return count;
}
}
The algorithm should be:
Having correct input, find all multiples of it that are in range [500, 1000]. Count them.
It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.
Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.
public static void main(String args[]) {
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while (input < 100 || input > 200) {
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count++;
}
System.out.println(input + " fits " + count(input) + " times");
}
private static int count(int input) {
int result = 0;
int temp = input;
while (temp <= 1000) {
if (temp >= 500) {
result++;
}
temp += input;
}
return result;
}
According to your code, I see some issues. I'll point them out, as it is important for practicing Java.
Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,
It's important to stick to Java styling. Don't put too many empty lines, keep indents.
Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.

Checking if String entered is a binary numer, getting incorrect output

I am trying to write a program that will check if the user-entered string is a binary number, and if it is, it will output the number of 1s in the number. I had this working fine with an integer value, but since an int can't hold more than 2 billion or whatever the max value is, I am trying to rewrite it to work with Strings.
As of right now, any number I enter will output "Number entered is not binary." and when I enter 0, I will get a StringIndexOutofBoundsException. I am a fairly novice programmer, so forgive any obvious errors I may have missed, I am just asking for a possible solution to my problem or a push in the right direction. Here is my code (after trying to make it work with Strings rather than integers):
import java.util.*;
public class BinaryHW {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
//the method I used to check whether or not user entered a binary
//number requires changing the value of 'bin'.
//Therefore, 'origBin' set equal to 'bin' for later use.
String origBin = bin;
int count = 0;
boolean isBinary = true;
/* if bin = 0, then this loop will be skipped because
* 0 is a binary number and need not be checked.
*/
while (Integer.parseInt(bin) != 0) {
int lastDigit = bin.charAt(bin.length() - 1);
if (lastDigit > 1) {
System.out.println("Number entered is not binary.");
isBinary = false;
break;
} else {
bin = bin.substring(bin.length() - 2);
}
}
//Again, the method I used to count the 1s in the bin number
//requires changing the value of origBin, so origBin2 is introduced
String origBin2 = origBin;
for (int i = 0; i < origBin.length(); i++) {
if (origBin.charAt(origBin.length() - 1) == 1) {
count ++;
origBin2 = origBin.substring(origBin2.length() - 2);
} else {
origBin2 = origBin.substring(origBin2.length() - 2);
}
}
if (isBinary)
if (count == 1)
System.out.println("There is "
+ count + " 1 in the binary number entered.");
else
System.out.println("There are "
+ count + " 1s in the binary number entered.");
}
}
I think you are overcomplicating things... simply iterate through your binary string, and keep track of the number of 1's reached. If a number other than 0 or 1 is found, report that input is a non-binary number. Below is a snippet which accomplishes this:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
int oneCount = 0;
boolean validBinaryNum = true;
for (int i = 0; i < bin.length() && validBinaryNum; i++) {
char currentChar = bin.charAt(i);
if (currentChar == '1') oneCount++;
else if (currentChar != '0') {
validBinaryNum = false;
}
}
if (validBinaryNum && bin.length() != 0) {
System.out.println("Number of 1's: " + oneCount);
} else {
System.out.println("Number is not binary");
}
}

Categories

Resources