Very amateur coder here,
I'm in the process of making a simple program to tell whether a number is positive, negative, odd or even. So far everything works apart from positive odd numbers, but cant figure out why ?
Also, how would i loop it ? would i use a for or while loop ?
Thanks
package weekeleven;
import java.util.Scanner;
public class week111 {
static int number;
static String pE;
static String pO;
static String nE;
static String nO;
static String eR;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
number = -input.nextInt();
pE = ("Positive Even");
pO = ("Positive Odd");
nE = ("Negative Even");
nO = ("Negative Odd");
eR = ("Error");
Object x = null;
x=getSignAndParity(x);
System.out.println(x);
}
public static String getSignAndParity(Object x) {
if ((number > 0) && (number % 2 == 0)) { //negative and even
return nE;
} else if((number < 0) && (number % 2 == 1)) { // positive and odd
return pO;
} else if((number < 0) && (number % 2 == 0)) { // positive and even
return pE;
} else if((number > 0) && (number % 2 == 1)) { // negative and odd
return nO;
} else { // other cases
return eR;
}
}
}
There are multiple issues with your code causing it not to work as expected.
1) You are using mod 2 on negative numbers to check if a negative number is even or odd. But that will not work. For e.g., -7 mod 2 = -1 (which is neither 1 nor 0)
2) You are negating the user's input :
number = -input.nextInt();
and you flipped the signs >, < which is unnecessary
3) You should not be passing the int input as Object. You could just simply:
public static String getSignAndParity(int x)
Removing all the superfluous and unnecessary declarations and code, you can have this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
System.out.println(getSignAndParity(number));
}
public static String getSignAndParity(int num) {
if(num == 0)
return "Error";
String sign = num>0?"Positive":"Negative";
String parity = Math.abs(num)%2==0?"Even":"Odd";
return sign + " " + parity;
}
Change with this
else if((number > 0) && (number % 2 == 1)) { // positive and odd
return pO;
}
For positive odd numbers and for looping you need either existing the code or have a condition that is taken from scanner and then close the scanner.
scanner : https://www.javatpoint.com/Scanner-class
You have to change positive odd like this:
else if((number < 0) && (number % 2 == -1)) { // positive and odd}
Related
Everything works in this class except for the final else statement. This is a recursive java letter tester. The program tests a user's word for all three letters (e, l, f). So far, Program throws exception error string index out of bounds if the word doesn't contain e, l and f
import java.util.Scanner;
public class FrettyRecursionMethod {
static boolean e = false;
static boolean f = false;
static boolean l = false;
static int n = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userWord;
System.out.println("Enter a single word.");
userWord = input.nextLine();
elfish(userWord, 0);
} // end main
public static void elfish(String userWord, int n) {
char ee = userWord.charAt(n);
if (ee == 'e' || ee == 'E') {
e = true;
} // end if
else if (ee == 'f' || ee == 'F') {
f = true;
} // end else if
else if (ee == 'l' || ee == 'L') {
l = true;
} // end else if
if (e == true && f == true && l == true) {
System.out.println("Your word is elfish!");
}
else if (n < userWord.length()) {
elfish(userWord, n + 1);
}
else
{
System.out.println("Your word isn't elfish.");
} // end if-else else
} // end elfish method
}// end class
I'm pretty sure it's because you don't terminate your recursion properly. In order to check the n+1 character, the current n has to be n-2 or the value of n+1 is going to be out of range. That's because charAt() is limited to at most n-1.
So you want to make sure that n is less than n-1 before you pass it.
else if (n < userWord.length()-1) {
elfish(userWord, n + 1);
Replace n < userWord.length() with n < userWord.length()-1
Why? If input word has 3 letters, the last index you can access of it is 2. But the length() method returs the number of lettets that string contains, and it cointains 3 letters.
So 2 < 3 == true and program calls the eflish function with n=3, and it throws Index Out Bounds Exception.
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.
Input
1
2
3
0
Output
odd
even
odd
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num;
for (; ; ) {
Scanner reader = new Scanner(System.in);
num = reader.nextInt();
if (num % 2 == 0) {
System.out.println("even");
}
else if(num == 0){
break;
}
else{
System.out.println("odd");
}
}
}
}
The issue with your posted code is addressed in the comment (checking num % 2 == 0 first), but in this case we can improve upon your solution. First, it's "idiomatic" in Java1 to use a while loop with a test after assignment. Second, it's possible to use a ?: conditional operator (a ternary) and remove the remaining if / else. Like,
int num;
Scanner reader = new Scanner(System.in);
while ((num = reader.nextInt()) != 0) {
System.out.println(num % 2 == 0 ? "even" : "odd");
}
1I don't know who defines idioms, but I didn't invent it. And I've seen this construct in JDK source.
int num;
Scanner reader = new Scanner(System.in);
for ( ; ; ) {
num = reader.nextInt();
if (num == 0) {
break;
} else if (num % 2== 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
Your problem is the sequence of your if/else conditions. If the first input is 0, 0 % 2 returns true - so it will never break.
Also, you do not need a new Scanner every time. You can take it out of the loop and reuse it.
You need to check if the value is zero before checking if the value is even.
For example:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int num;
while(true) {
num = reader.nextInt();
if(num == 0) break;
else if(num % 2 == 0) System.out.println("even");
else System.out.println("odd");
}
}
Made a program that prints if a number is weird or not. If the number is odd, it's weird. If the number is even and inclusively between 2 and 5, it is not weird. If it's even and inclusively between 6 and 20, it's weird, and if it's even and greater than 20, it's not weird. The problem I'm having here is that instead of the output displaying "This number is weird/not weird", I get "Weird" or "Not Weird" on one line, followed by "This number is 0" if it's even, or "This number is 1" if it's odd.
public Weird(int num)
{
n = num;
}
public int EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && answer >= 2 && answer <= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && answer >= 6 && answer <= 20)
{
System.out.println("Weird");
}
else if (check == 0 && answer > 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
return check;
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You actually return int which is value of check field. This is either 1 or 0.
When you call this line-
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
It prints either This number is 0 or This number is 1.
You can get desired output by two ways-
Way 1-
Change return type of method to void EvenOrOdd() like-
public void EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n<= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && n>= 6 && n<= 20)
{
System.out.println("Weird");
}
else if (check == 0 && n> 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
}
and call method in main as-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
w.EvenOrOdd();
a.EvenOrOdd();
}
Way 2- Change return type of method to String as-
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n>= 2 && n<= 5)
{
return "Not Weird";
}
else if (check == 0 && n>= 6 && n<= 20)
{
return "Weird";
}
else if (check == 0 && n> 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
And main method remains same-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You should return that string rather than printing it. In your function, you are returning an int but rather you should write a String. Besides that everything looks good but you can decrease the number of check like below:
public Weird(int num)
{
n = num;
}
public String EvenOrOdd()
{
int check = n % 2;
if (check == 1 || (check == 0 && n >= 6 && n <= 20)) {
return "Weird";
}else{
return "Not Weird";
}
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
The value you return from a method will kind of "replace" the method call. Because you returned check:
return check;
The calls:
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
are basically:
System.out.println("This number is " + 0);
System.out.println("This number is " + 1);
You seem to be confused about returning and printing. Your method should look like this:
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n <= 5)
{
return "Not Weird";
}
else if (check == 0 && n >= 6 && n <= 20)
{
return "Weird";
}
else if (check == 0 && n > 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
Now the two calls is basically:
System.out.println("This number is " + "Weird");
System.out.println("This number is " + "Not Weird");
I'm trying to write a program that asks the user to enter a number, then I need to create a method called isPrime to create the calculation and print out the result in main. I'm sure it's something small that I'm missing, but I can't get it to produce an accurate result.
public static void main(String[] args) {
System.out.print("Enter number: ");
int num = s.nextInt();
if (isPrime(num) == true) {
System.out.println("Number is prime");
} else if (isPrime(num) == false) {
System.out.println("Number is not prime");
}
}
public static boolean isPrime(int num){
for(int i = 2; i <= num/2; i++) {
if (num%i != 0) {
return true;
}
}
return false;
}
Use an if and else (don't retest your boolean condition in the first case). And don't test for == true in an if. This
if(isPrime(num) == true)
{
System.out.println("Number is prime");
}
else if(isPrime(num) == false)
{
System.out.println("Number is not prime");
}
Should just be
if (isPrime(num)) {
System.out.println("Number is prime");
} else {
System.out.pritnln("Number is not prime");
}
or even something like
System.out.print("Number is ");
if (!isPrime(num)) {
System.out.print("not ");
}
System.out.println("prime");
If you want to put the braces on their own lines go ahead. As for your isPrime method; you have your return conditions reversed (and the test as well). Also we can optimize it a bit. Unroll the first even test, because then we can skip every other element. Also we only need to test to the square root of the input number. Like,
public static boolean isPrime(int num) {
if (num == 2) {
return true; // two is prime.
}
if (num < 1 || num % 2 == 0) {
return false; // all other even numbers are not prime.
}
for(int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
The isPrime(int num) method may need to check if num % i == 0 instead of if num % i != 0 because many non-prime numbers will pass the condition and return true.
As an example, if isPrime(9) is called, the conditional will check if 9 % 2 != 0, which is true, and the method will say that 9 is prime when it's not.
As a result, you could try changing the method to something like this:
public static boolean isPrime(int num)
{
for(int i = 2; i <= num/2; i++)
{
if (num%i==0)
{
return false;
}
}
return true;
}
You should change your "if (num%i!=0)" condition to if(num % i == 0)
See the following code:
public class Prime {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
i tried to make a simple program,which check if the input number from the user is a binary number and that number is in correct binary format -> without leading zeros. That below is my code,but it doesn't work. I would appreciate if someone could help.
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
num = sl.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));// i want to get the first digit from the input
if (firstDigit>0||firstDigit==1 ){
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
} else System.out.printf("WARNING: The number starts with 0");
}
}
There are a better solution, you can check if your input contain only 0 and 1 and the input great then 0 then valide number, so instead you can use String for example :
String num;
Scanner sl = new Scanner(System.in);
num = sl.next();
if (num.matches("[01]+") && !num.startsWith("0")) {
System.out.println("Correct number :" + num);
}else{
System.out.println("Not Correct number!");
}
num.matches("[01]+") will check if your input contain only 0 and 1.
!num.startsWith("0") this to answer this part without leading zeros
Test:
10010 -> Correct number :10010
00001 -> Not Correct number!
11101 -> Correct number :01101
98888 -> Not Correct number!
You can try something like this:
public static void main(String args[]) {
boolean binary=true; // boolean for final decision
String input;
int counter=0; // to count how many leading zeros there are in the input
int target = 5; // specify how many leading zeros allowed!!
Scanner in = new Scanner(System.in);
input = in.nextLine(); // take the entire line as a String
//first loop through the whole input to check for any illegal entry (i.e. non digits)
for(char digit : input.toCharArray()){
if(!Character.isDigit(digit)){ // catch any non-digit !
System.out.println("Illegal Input Found!"); // inform user and exit
System.exit(0);
}
if(digit!='0' && digit!='1'){ // check if it's not 1 and not 0
binary = false;
}
}
// now if there are no illegal inputs, check if it starts with leading zeros
if(input.charAt(0)=='0'){ // potential leading zeros, check the rest
while(input.charAt(counter)=='0'){ // while there are followed zeros
counter++;
if(counter>target && binary){ // leading zeros only in case it's a binary
System.out.println("Illegal Leading Zeros!");
System.exit(0);
}
}
}
// now if your program reach this point that means the input is valid and doesn't contain leading zeros in case it's a binary
if(binary){
System.out.println("It is a binary number");
}
else{
System.out.println("It is NOT a binary number");
}
}
Test:
01010101 -> It is a binary number
01010105 -> It is NOT a binary number
0000001 -> Illegal Leading Zeros!
0000005 -> It is NOT a binary number
000000A -> Illegal Input Found!
Why not simply use the standard library methods?
static boolean isValidBinary(final int input) {
final String binary = String.valueOf(input);
return binary.replaceAll("[01]", "").isEmpty() && !binary.startsWith("0");
}
you should not use sl.nextInt(); it will transfer '011' to 11, so when user input '011', the variable 'num' get the int value 11.
You should simply use sl.next() to get the input of user.
I think you need to check your "if" condition before the while, because you don't want that the number starts with 0, right? so... just ask for it, I have tryied and worded fine to me:
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
String input = sl.next();
num = Integer.parseInt(input);
String firstDigit = (input.length() > 0 ? input.substring(0, 1) : "" );
if (firstDigit.equals("0")) {
System.out.printf("WARNING: The number starts with 0");
} else {
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
}
}
}
The rest of your code Fulfills its mission! It tells you if the number is binary or not, and now plus tells you if your code begins with useless zeros
import java.util.*;
public class BinaryTest {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
int count=0;
boolean check=true;
System.out.print("Enter a number: ");
int num=input.nextInt();
for(int i=0; i<=num; i++){
count=num%10;
if(count>1) {
check=false;
break;
}
else {
check=true;
}
num=num/10;
}
if(check)
System.out.println("Binary");
else
System.out.println("Not Binary");
}
}