How do I change the code....
if (yourAnswer = numberOne + numberTwo)
{
System.out.println("That is correct!");
counter = counter + 1;
}
else
{
System.out.println("That is incorrect!");
}
This does not seem to be working for me. Can anyone help me?. The debugger is saying:
RandomNumbersProgramThree.java:21: error: incompatible types: int cannot be converted to boolean".
You cannot associate a number with a Boolean value. A boolean is true or false, not a number, however you can create a variable that indicates if a certain number represents true or false. Is this your entire program? I would like to see what "yourAnswer", "numberOne", and "numberTwo" are stored. but for now I will write a pseudo-program to explain the theory.
import java.util.*;
public class ExampleProgram
{
public static void main(String[] args)
{
System.out.println("Please enter two numbers");
Scanner answer = new Scanner (System.in);
int yourAnswer = answer.nextInt();
int numberOne = 1;
int numberTwo = 2;
if (yourAnswer == (numberOne + numberTwo))
{
System.out.println("That is correct!");
}
else
{
System.out.println("That is incorrect!");
}
}
}
This program will ask the user to input a number, for example the number "3". It will then compare that number to the two numbers you declares, "numberOne" which equals the value of one, and "numberTwo" which equals the value of two. Therefore, in the "IF" statement it says, "If (yourAnswer == (numberOne + numberTwo))" which means that 1 + 2 = 3, if the users answer is 3, then 3 = 3 and the result will come back as true.
In the if statement, you are using an '=' sign, this type of equal sign is not a comparison '=' but is used to set a value to an variable. ie, int x = 2;
The type of equals you need is the type that is used in comparisons, which is ==. You always use == when dealing with boolean comparisons
Related
The help I need is in JAVA coding, please. I'm having an extremely hard time learning this through online class instead of in person due to the pandemic going on. Any help is appreciated and thank you for taking the time to help a struggling student/parent!
Create a Scanner object that will be used for user input.
Prompt the user to enter an integer and store the value in a variable named num.
Call a method named getCount (details are given below) that will return the number of individual digits in the number that is between 3 and 6 (inclusive)
Display the original number and the number of digits between 3 and 6.
Create the method getCount that has a parameter of type int and returns a value of type int. This method will do the following:
Declare an integer variable named count and initialize it to 0.
Within a while or do-while loop, do the following:
Get the last digit of the parameter by getting the remainder after dividing by 10. Use the % operator to do this.
Call the inRange method, passing this digit as a parameter. If the inRange method returns true, add 1 to
count.
Use integer division by 10 on the parameter to change its value by getting rid of the last digit. Use the / operator to do this.
Stay in the loop as long as the parameter is greater than 0.
Create the method inRange that has a parameter of type int and returns a value of type Boolean. This method will return true if the parameter is between 3 and 6 (inclusive).
import java.util.*;
public class five {
public static void main(String[] args) {
int num;
Scanner kb = new Scanner(System.in);
System.out.print("Enter an integer: ");
System.out.print("Your number is ");
} // end main
public static boolean getCount(int) {
return int >= 3 && <= 6;
} // end getCount method
public static boolean inRange(int) {
return boolean
} // end inRange method
}
The output I'm attempting to get is
Enter an integer: 435678123
Your number is 435678123
It has 5 digits between 3 and 6.
Something like this would do the trick:
import java.util.Scanner;
public class five{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int x = 0;
System.out.print("Enter an integer: ");
x = sc.nextInt();
System.out.println("Your number is " + x);
System.out.println("It has " + getCount(x) + " digits between 3 and 6");
}
public static int getCount(int x){
int count = 0;
while(x > 0){
count += inRange(x%10) ? 1 : 0;
x/=10;
}
return count;
}
public static boolean inRange(int x){
return x >= 3 && x <= 6;
}
}
Output:
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I need help making a loop that looks at each value from 1 to number-1.
Also how to test each value to see if it is a
divisor of number, and if it is, adding it to the sum.
This is what I have so far:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Please enter a positive integer: ");
int n = input.nextInt();
while (n < 0) {
System.out.println(n + " is not positive.");
System.out.print("Please enter a positive integer: ");
n = input.nextInt();
}
}
You can use this as a starting block for your application:
package Testers;
import java.io.Console;
public class Application {
public static void main(String[] args)
{
Console console = System.console();
if (console == null)
{
System.err.println("No console.");
System.exit(1);
}
boolean keepRunning = true;
while (keepRunning)
{
String name = console.readLine("Type your positive integer");
try{
int integer = Integer.parseInt(name);
if(integer < 0){
System.out.println("You must specify a positive integer!");
}
for(int i = 1; i<integer; i++){
// our variable "i" is smaller than "integer". This will parse all the numbers between one and "integer" -1.
if(i % 2 == 0){
//"i" IS divisible by 2. Of course, you can change this value to what you want to change it to.
//Here you can add it to a sum
}else{
//"i" is not divisible by 2. Of course, you can change this value to what you want to change it to.
}
}
}catch(NumberFormatException e){
System.out.println("You must specify a positive integer!");
}
}
}
}
If you want to do something for a known number of times, it is mostly a good idea to use a for loop. If you want to do something for number 1 to n-1, the loop could look like
for(int i = 1; i < n; i++) { // do stuff }
Note that it starts counting from 1 and stops as soon as i is greater or equal than n.
In order to know whether a number, say n, is divisible by some number, say k, the modulo-operator % could be used. If n % k == 0 this means that n is divisible by k. With an if-statement this can be tested and when you have some sum variable you can add whatever you want to that variable to sum things up.
Hope that helps
import java.util.Scanner;
public class lesserString2 {
public static void main(String args[]) {
Scanner r = new Scanner(System.in);
int y = 0;
int result = 0;
String s = null;
String q = null;
while (y < 2) {
s = r.nextLine();
y = y + 1;
q = r.nextLine();
y = y + 1;
}
if (y >= 2){
result = s.compareTo(q);
}
if(result == 0) {
System.out.println("The strings are equal, please try again.");
} else if(result == 1) {
System.out.println("Lesser is: " + s);
} else if(result < 0) {
System.out.println("Lesser is: " + q);
}
}
}
I am getting mixed results when I try to submit two different sentences through standard input.
For instance...
C:\Users\...>java lesserString2
how does the cat jump
very quickly i think
Lesser is: very quickly i think
C:\Users\...>java lesserString2
Jack Sprat can eat no fat
His wife can eat no lean
Why didn't it work the second time? How can I make it work every time? The second one I tried literally outputs nothing... It is just a blank line.
The two main issues are that you're using result == 1 where you need to be using result > 0 (the positive value from compareTo may not be 1; more in item #3.2 below), and that you have your comparisons backward, so you're actually showing the "greater" of the two strings rather than the lesser (item #3.1).
But that code has a variety of other issues, here's a list:
The while (y < 2) loop is completely unnecessary: y starts at 0 and you add 1 to it twice, so it will always execute exactly once.
The if (y >= 2) branch is completely unnecessary (see #1).
You're misusing the return return value of compareTo in two different ways:
When you get a value greater than 0, you're saying s is the "lesser" string. That value indicates s is the greater string.
You're comparing it == 1, but compareTo's contract does not guarantee that it will be 1, just that it will be a positive number if s is greater than q, 0 if they're equal, or a negative number if s is less than q. The positive number may not be 1.
In Java, class names are initially-capped. So LesserString2, not lesserString2.
It's always best to use meaningful names for your variables.
The reason you're not getting any output is #3.2 in the above list. You're getting a positive value, but not 1.
Here's a version with the issues above addressed:
import java.util.Scanner;
public class LesserString2 {
public static void main(String args[]) {
Scanner inputScanner = new Scanner(System.in);
int result;
String firstString;
String secondString;
firstString = inputScanner.nextLine();
secondString = inputScanner.nextLine();
result = firstString.compareTo(secondString);
if (result == 0) {
System.out.println("The strings are equal, please try again.");
} else if (result < 0) {
System.out.println("Lesser is: " + firstString);
} else { // No need for: if (result > 0) {
System.out.println("Lesser is: " + secondString);
}
}
}
Problem is in your condition.
you need to change if(result == 1) to if(result >0)
Here is the documenation of the return value. It does not only return -0, 0, 1
the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
If you would print the result you would notice that the result has the value of 2.
You need to change this else if(result == 1) part to else if(result > 0)
EDIT: also you need to swap the print of the Lesser value since you are allways writing the lexicographically higher value as the lesser value.
in the compareTo method, the result can be either
Less than 0, if compareTo sees that the instance is "lesser" than the parameter.
Bigger than 0, if compareTo sees that the instance is "greater" than the parameter. or
Equals to 0, if compareTo sees that the instance is equal.
So change
} else if(result == 1) {
to
} else if(result > 0) {
How to find whether a number is odd or even, without using if condition or ternary operators in Java?
This question is given by my teacher. He also give me a hint that it is possible by using a bitwise operator.
There are few ways to not use if and get behavior that will be same as if if was used, like ternary operator condition ? valueIfTrue : valueIfFalse or switch/case.
But to be tricky you can also use arrays and try to figure some transformation of our value to proper array index. In this case your code could look like
int number = 13;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);
output:
13 is odd
You can change number % 2 with number & 1 to use suggestion of your teacher. Explanation of how it works can be found here.
Consider a number's representation in binary format (E.g., 5 would be 0b101).
An odd number has a "1" as its singles digit, an even number had a zero there. So all you have to do is bitwise-and it with 1 to extract only that digit, and examine the result:
public static boolean isEven (int num) {
return (num & 1) == 0;
}
int isOdd = (number & 1);
isOdd will be 1 if number is odd, otherwise it will be 0.
Did you mean something like this?
boolean isEven(int value) {
return value % 2 == 0;
}
boolean isOdd(int value) {
return value % 2 == 1;
}
Every odd number have 1 at the end of its binary representation.
Sample :
public static boolean isEven(int num) {
return (num & 1) == 0;
}
Just saw now 'Without using IF'
boolean isEven(double num) { return (num % 2 == 0) }
Just a quick wrapper over the already defined process...
public String OddEven(int n){
String oe[] = new String[]{"even","odd"};
return oe[n & 1];
}
I would use:
( (x%2)==0 ? return "x is even" : return "x is odd");
One line code.
Method 1:
System.out.println(new String[]{"even","odd"}[Math.abs(n%2)]);
Method 2:
System.out.println(new String[]{"odd","even"}[(n|1)-n]);
Method 1 differs from the accepted answer in the way that it accounts for negative numbers as well, which are also considered for even/odd.
import java.util.Scanner;
public class EvenOddExample
{
public static void main(String[] args)
{
System.out.println("\nEnter any Number To check Even or Odd");
Scanner sc=new Scanner(System.in);
int no=sc.nextInt();
int no1=no;
while (no>1)
{
no=no-2;
}
if(no==0)
{
System.out.println(no1 +" is evenNumber");
}
else
{
System.out.println(no1 +" is odd Number");
}
}
}
you can also use bitwise shift operators
(number >> 1)<<1 == number then even else odd
# /* **this program find number is odd or even without using if-else,
## switch-case, neither any java library function...*/
##//find odd and even number without using any condition
class OddEven {
public static void main(String[] args) {
int number = 14;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);
}
}
/**************OUTPUT*************
// 14 is even
// ...................
//13 is odd
I'm an aspiring java user taking college courses and I've run into a problem. My prof. told us to write a java program that detects a 5 digit number based palindrome. I've written something but it won't work the way I've planned. Could I get some help please? Using netbeans IDE.
package palindrome;
import javax.swing.JOptionPane;
public class Palindrome {
public static void main(String[] args) {
String stringNumber;
int number;
String stringPal;
int palindrome;
stringNumber = JOptionPane
.showInputDialog("Please, if you will, enter a five digit palindrome: ");
number = Integer.parseInt(stringNumber);
if (number < 10000 && number > 99999) {
System.out
.println("Your number is invalid, please enter a FIVE digit number: ");
} else if (number % 10 == number % 100) {
System.out.println("your number: " + number + "is a palindrome");
} else {
System.out.println("You FAIL loser");
}
}
}
Your palindrome logic is incorrect. You check if the remainder when divided by 10 equals the remainder when divided by 100 - that is the case if and only if there is a 0 in the tens digit. That is not the definition of a palindrome.
As already pointed out, that your logic for palindrome is wrong.
What you need to check is if the string/number is same when reversed.
So, suppose you want to check whether the a string is palindrome, reverse it and check if it is same as the original string.
You should try to complete this template:
boolean isPalindrome(String s){
String reverseString = reverseString(s);
if(reverseString.equals(s)){
return true;
}
return false;
}
String reverse(String s){
//add code to reverse String. (and optionally check if it is Integer, if it is a requirement)
}
You can now google how to reverse a string.
PS: You might wanna take a look at StringBuilder class.
i don't understand, how number % 10 == number % 100, implies palindrome, but all it does is compare the value of the last 2 digits to the value of the last 1 digit.
My advice would be to take input as a string or char array and the compare the last element of the string to the first, and then continue until you hit the middle
here's some psudo-code:
isPalindrome = true;
for i=0 to stringLength
if(input[i] != input[length - i - 1])
isPalindrome = false;