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) {
Related
Beginner coder here. I'm trying to differentiate when a user inputs a value and does not input a value.
Right now the integer variable = 0 when there is no specified value input by the user.
But if the user inputs 0 as their variable, I need it to be different.
if(exam1Input == 0){
exam1Per = 0;}
if(exam2Input == 0){
exam2Per = 0;}
if(finalExamInput == 0){
finalExamPer = 0;}
if(labsInput == 0){
labsPer = 0;}
if(projectsInput == 0){
projectsPer = 0;}
if(quizzesInput == 0){
quizzesPer = 0;}
if(attendanceInput == 0){
attendancePer = 0;}
I did this multibranch if statement to covert the value of the percentage grade weights to zero if the input was zero(i.e. no input at all).
However I come across a problem of when the user inputs "0" as their actual grade. I can't let the percentage weight be 0, I still need it to be the certain grade percentage.
e.g. if their test average is 0, i still need to calculate their percentage based on the grade 0.
So how could I be more specific and able to differentiate between a missing input versus an actual input?
I want zero to be the actual grade not as a missing input.
An easy solution would be to use a different default value that would be invalid input from the user. e.g:
static final int NO_INPUT = -1;
int exam1Input = NO_INPUT;
/**Prompt the user for input somewhere around here*/
if(exam1Input == 0) ...
Now, exam1Input will only be 0 if the user explicitly made it 0, and -1 otherwise.
Or, use an OptionalInt instead of an int. This sort of scenario is what they are for.
OptionalInt input = OptionalInt.empty();
// input = Optional.of(someValue); if set
If (input.isPresent()) {
int i = input.getAsInt();
// use the value
}
The method CountQiftPositiv is returning 0 no matter what inputs I type. What am I doing wrong here?
import java.util.Scanner;
public class QiftPositivCount
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
final int SENTINEL = -9999;
int x = 0;
int count = 0;
do
{
System.out.print("Type numbers (-9999 to end) : ");
x = scan.nextInt();
if(x == SENTINEL)
{
break;
}
count++;
}while (x != SENTINEL);
if(count == 0)
{
System.out.println("You didnt type any number");
}
else
{
System.out.println("There are " + count + " numbers typed , and the numbers that fulfill the conditon are "
+ CountQiftPositiv(x));
}
}
private static int CountQiftPositiv(int nr)
{
int poz = 0;
if(nr % 2 == 0 && nr % 3 == 0 && nr > 0)
{
poz++;
}
return poz;
}
}
Your do-while loop throws out all user input except the last integer entered (if any). Since the only way out of that loop (not counting exceptions) is the sentinel value -9999, that is the only value you will ever assign to x and pass to CountQiftPositiv.
CountQiftPositiv, meanwhile, only returns 1 if for positive integers divisible by 6. For every other value, including your sentinel, it returns 0.
Other Sentinel Problems
The use of a sentinel value is almost always a mistake (unless that's specifically part of your assignment). Sooner or later, that "impossible" input will actually show up.
Since your goal is to continue the loop until the user is done (a "yes or no" question), use a local Boolean variable, and test that. Also, java.util.Scanner has lots of useful methods for exactly this kind of situation, for example:
boolean done = false;
while (! done) {
if (scan.hasNextInt()) {
// Store scan.nextInt() for use later. See below.
} else {
// No more (valid) inputs.
done = true;
}
}
This loop could actually be shortened to just while (scan.hasNextint()) { ... }, but storing your loop's continue-or-end condition in a variable is handy for more complex exit decisions.
Storing User Input
You aren't storing more than one user input, ever. Create a List of some sort to store them, and then operate on that list.
java.util.List<Integer> numbers = new java.util.LinkedList<Integer>();
Later, in the "while not done" loop:
if (scan.hasNextInt()) {
numbers.add(scan.nextInt());
} else {
done = true;
}
Counting User Inputs
No need for count --- your collection of integers will store that for you:
if (numbers.size() == 0) {
System.out.println("You didn't type any numbers!");
}
Printing Output
Finally, output each number only if it fulfills that weird condition. This assumes you rewrite CountQiftPositiv to return a boolean (which it almost does already):
for (int number : numbers) {
if (CountQiftPositiv(number)) {
System.out.println(number);
}
}
You'll probably want to rename that method now that it no longer counts anything.
I leave the rest to you.
PS: It's almost always a good idea to separate input, processing, and output into (at least) three different methods, especially when you're learning. It's vastly easier to understand a bunch of short methods than one do-it-all method, and makes debugging problems like this much easier.
You have return 0 because last input is -9999 a negative number, and this condition if(nr % 2 == 0 && nr % 3 == 0 && nr > 0) is usually false.
Try to change the SENTINEL nymber:
You're using CountQiftPositiv(x) outside of the while loop.
With the code you have, it's the same thing as you call CountQiftPositiv(-9999)
I'm suggesting you to do something like:
do {
System.out.print("Type numbers (-9999 to end) : ");
x = scan.nextInt();
if(x == SENTINEL) {
break;
}
if (CountQiftPositiv(x) > 0) {
count++;
}
} while (x != SENTINEL);
I suggest also to rework your loop since the break is not required if you use the x = scan.nextInt(); wisely.
CountQiftPositiv(x) sends -9999 in because its the last x value always -> as you stop taking inputs when x = -9999
nr < 0 -> poz will stay at 0
I've made a temp variable which will take your input, if the input is not equal to the SENTINEL variable, it will set x = temp thus removing the -9999 value from being passed into CountQiftPositiv().
Also when you are checking for a number that is a factor for multiple numbers, all you have to do is multiply the numbers together and check the mod for that number.
For 2 and 3, all you have to check is 6.
import java.util.Scanner;
public class QiftPositivCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int SENTINEL = -9999;
int temp;
int x = 0;
int count = 0;
do {
System.out.print("Type numbers (-9999 to end) : ");
if((temp = scan.nextInt()) == SENTINEL){
break;
}else {
x = temp;
count++;
}
} while (temp != SENTINEL); // not really needed as you have the break statement
if (count == 0) {
System.out.println("You didnt type any number");
} else {
System.out.println("There are " + count + " numbers typed , and the numbers that fulfill the conditon are "
+ CountQiftPositiv(x)); // This was sending -9999 which will always evaluate to false in the function
//poz will stay at 0 the entire time
}
}
private static int CountQiftPositiv(int nr) {
int poz = 0;
//if(nr % 6 && nr > 0){
if (nr % 2 == 0 && nr % 3 == 0 && nr > 0) {
poz++;
}
return poz;
}
}
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
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 having a huge problem here. Basically what i have to do is have a user enter a number... the program then takes the number, reads if it's negative or positive. If negative it sets the previously false negval to true and moves on. it then reads the number again, checking for leading zeros, if there are any it removes them. It then takes what is left and checks to see if the string is less than the max amount of characters aloud, if it is then it loops to count the spaces, while it counts the spaces it also makes sure they are digits . if the string is bigger than the allowed amount of characters the program stops checks and prints a 0
my problem is that it keeps jumping to the 0 output even though the string length is a valid length
here is what i have.
String snum;
System.out.print("Please enter a number here : ");
snum = console.next();
System.out.println(getIntnum(" The number entered was: "+snum));
Other generic stuff
final String maxInt = "2147483648";
final String minInt = "-2147483648";
boolean negval = false;
int n;
int count;
int num = 1;
int value;
if(snum.charAt(0) == '-' || snum.charAt(0) == '+')
{
if(snum.charAt(0) == '-')
{
negval = true;
}
else
{
snum = snum.substring(1, snum.length());
}
}
while (snum.charAt(0) == '0')
{
snum = snum.substring(1, snum.length());
}
n = snum.length( );
if (n < 10)
{
count = 0;
if (count < n)
{
if (Character.isDigit(snum.charAt(count)))
count++;
}
}
else
{
num = 0;
}
if(maxInt.compareTo(snum) >= 0 && minInt.compareTo(snum) <= 0)
{
num = Integer.parseInt(snum);
}
if(negval == true)
{
num = num * -1;
}
value = num;
return value;
}
}
You are comparing Strings which don't work the same way as comparing numbers. For example, "10" < "2" because '1' < '2' and this means that "-1" < "-2147483648" and "3" > "2147483647"
It's difficult to suggest what you should do instead as it's not clear to me why you are doing half of the code you have e.g. Can you say how your code is different from
try {
return Integer.parseInt(s);
} catch (NumberFormatException ignored) {
return 0;
}
Your main problem is that you're using a string comparison to compare numbers. Also, since you already know that the number is positive, there's not much point comparing it to minInt. Lastly, you have the wrong value for maxInt.
Simply use Integer.parseInt(snum)
final String maxInt = "2147483648";
MAX_INT is 2147483647.
Second of all, do not use String comparison to compare numbers. Use it like this:
if (Integer.parseInt(maxInt) >= Integer.parseInt(snum)) {
num = Integer.parseInt(snum);
}