reading from a file wont read the first value Java - java

So i Have this code going on, I need it to open a file, and scan the two integers in the file, then I need it to store the two numbers. The numbers are restricted to between 1 and 10 for the first number and between 1 and 39 for the second number. I have a valueCounter to make sure that the correct number gets stored in the correct variable. For some reason, the code always returns
"Your Initial Fib is out of range, eneter # between 1-10"
Which would be appropriate if the first number was greater than 10 or less than 1, but regardless of what i change the first number to, the code returns the same line. The only time it wont return that line is when i change the 2nd number to to be between 1 and 10. So I can conclude that the code is skipping the first number, but i cant figure out why. Any being of higher intelligence that can help?
private static File inFile = null;
private static PrintWriter outFile = null;
private static int startValue;
private static int lengthValue;
public static void main(String[] args) throws IOException
{
inFile = new File( inFileName);
Scanner in = new Scanner (inFile);
outFile = new PrintWriter (outFileName);
int valueCounter = 1;
while (in.hasNextInt())
{
int value = in.nextInt();
if ( value <= 39 && value >= 1 && valueCounter == 2)
{
lengthValue = value;
valueCounter ++;
}
if ( value > 39 || value < 1 && valueCounter == 2)
{
System.out.println("You are asking for too many Fib, eneter # between 1-39");
in.close();
System.exit(1);
}
if ( value <= 10 && value >= 1 && valueCounter == 1)
{
startValue = value;
valueCounter ++;
}
if ( value > 10 || value < 1 && valueCounter == 1)
{
System.out.println("Your Initial Fib is out of range, eneter # between 1-10");
in.close();
System.exit(1);
}
}
}

It is because of operator precedence, the && is evaluated before the ||. This makes the following expression
if ( value > 10 || value < 1 && valueCounter == 1)
evaluated to true the second round, because first value < 1 && valuecounter == 1 is evaluated, which is false. Next, value > 10 is evaluated, which is true. Or-ing both results in true, and the body executes. Use parentheses to control the order of evaluation.

if ( value > 10 || value < 1 && valueCounter == 1)
Seems to be always true and since its a normal outer "if" at the end of code, its always being called. overthink your "if" and its appearance

Related

I want to check if a number is binary or not in decimal numbers but it didnt work

I want to check if a number if binary or not in decimal numbers but it didnt work
from numbera 1 to n.
for example from 1 to 10 we have 2 decimal numbers that contains 0,1.How can i change it?
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
int r = 0, c = 0, num, b;
int count=0;
Scanner sl = new Scanner(System.in);
System.out.println("Enter a number");
num = sl.nextInt();
for (int i = 1; i <= num; i++) {
if ((i % 10 == 0) || (i % 10 == 1))
c++;
r++;
i = i / 10;
}
if (c == r)
count++;
else{
}
System.out.println(count);
}
}
I am not a java dev so maybe my answer is not good.But you can use your number as str then check if the str is constituted only by 0 and 1
maybe this could help: : How to check if only chosen characters are in a string?
have a nice day
Here's how you can do it in an elegant way ...
// Function to check if number
// is binary or not
public static boolean isBinaryNumber(int num)
{
if(num == 1 || num == 0) return true
if (num < 0) return false;
// Get the rightmost digit of
// the number with the help
// of remainder '%' operator
// by dividing it with 10
while (num != 0) {
// If the digit is greater
// than 1 return false
if (num % 10 > 1) {
return false;
}
num = num / 10;
}
return true;
}
Here, will use 2 loops, one for range and one for checking if it's binary or not.
Instead of c and r, we will use flag and break in order to skip unnecessary iteration.
int count=0;
boolean flag = true;
for(int i=1;i<=num;i++)
{
for(int j=i;j>0;j=j/10)
{
// if remainder is not 0 and 1, then it means it's not binary
// so we set flag as false
// and using break to break out of the current(inner) loop, it's no longer needed to check remaining digits.
if (j%10 > 1)
{
flag = false;
break;
}
}
// if flag is true, that means it's binary and we increment count.
// if flag is flase, that means it's not binary
if(flag)
count++;
// here we reset flag back to true
flag = true
}
System.out.println(count);
You can also do as #jchenaud suggested. converting it to string and check if it only contains 0 and 1.

JAVA checking two numbers digit are the same

hi I am trying to solve Udemy exercise:
Write a method named hasSharedDigit with two parameters of type int.
Each number should be within the range of 10 (inclusive) - 99 (inclusive). If one of the numbers is not within the range, the method should return false.
The method should return true if there is a digit that appears in both numbers, such as 2 in 12 and 23; otherwise, the method should return false.
I am keep getting true while hasSharedDigit(9,99) I cant discover why..
public class SharedDigit {
public static boolean hasSharedDigit(int number1, int number2){
if((number1 <10 || number1 >99) && (number2 <10 || number2 >99)) {
return false;
}
int numberOneFirstDigit = number1/10;
int numberTwoFirstDigit = number2/10;
int numberOneLastDigit = number1%10;
int numberTwoLastDigit = number2%10;
if(numberOneFirstDigit == numberTwoFirstDigit || numberOneFirstDigit == numberTwoLastDigit || numberOneLastDigit == numberTwoLastDigit) {
return true;
} else {
return false;
}
}
}
If one of the numbers is not within the range, the method should
return false.
Replace
if((number1 <10 || number1 >99) && (number2 <10 || number2 >99))
with
if(number1 <10 || number1 >99 || number2 <10 || number2 >99)
Apart from this, you have missed numberOneLastDigit == numberTwoFirstDigit in the combination of conditions which are supposed to compare the digits i.e. the combination should be
if(
numberOneFirstDigit == numberTwoFirstDigit ||
numberOneFirstDigit == numberTwoLastDigit ||
numberOneLastDigit == numberTwoFirstDigit ||
numberOneLastDigit == numberTwoLastDigit
)
Treating numbers as text
The other Answer and comments solved your direct problem. Just for fun, we can take an entirely different approach.
The idea here is to treat the numbers as text. In doing so, we can address each of your two business rules:
Each number should be within the range of 10 (inclusive) - 99 (inclusive).
Numbers between 10 and 99 happen to have exactly two digits. One digit or 3+ digits means out-of-range.
if there is a digit that appears in both numbers
By collecting into a Set the code point of each character in the string that is our first number, we have a distinct collection for which we can get the intersection of the same for the second number’s string. If the intersection, the resulting modified Set, has a size over 0, then we know digits are shared.
To explain the code below… The codePoints method generates an IntStream, a sequence of int numbers, one for each code point number defined in Unicode for each character in our string that represents our input integer. The boxed call converts those int primitives into Integer objects. Adding those Integer objects to a Set automatically makes them distinct, weeding out automatically any duplicate digits.
See this code run live at IdeOne.com.
private boolean twoIntsAreInRangeAndShareDigits ( int n1 , int n2 )
{
String n1String = Integer.toString( n1 );
String n2String = Integer.toString( n2 );
// Check for negative numbers, meaning out-of-range, not 10-99.
if ( n1String.concat( n2String ).contains( "-" ) ) { return false; }
// Check for exactly 2 digits, meaning within range, 10-99.
if ( ( n1String.length() == 2 ) && ( n2String.length() == 2 ) )
{ // Numbers are within range.
// Check for common digits.
Set < Integer > n1CodePoints = n1String.codePoints().boxed().collect( Collectors.toSet() );
Set < Integer > n2CodePoints = n2String.codePoints().boxed().collect( Collectors.toSet() );
n1CodePoints.retainAll( n2CodePoints );
boolean sharesDigit = ( n1CodePoints.size() > 0 );
return sharesDigit;
}
else // Else 1 or 3+ digits mean numbers are out-of-range.
{ return false; }
}
I am not arguing that this approach is better, just interesting as a different way of thinking about the problem.
You're missing a comparison here. What you have is f1 == f2 || f1 == l2 || l1 == l2 but what's missing it l1 == f2, e.g. 12 and 23 would return false with your code because
1 != 2 (f1 == f2 fails)
1 != 3 (f1 == l2 fails)
2 != 3 (l1 == l2 fails)
your code is missing the 2 == 2 (l1 == f2) so add ... || numberOneLastDigit == numberTwoFirstDigit to the comparison condition.
As the others already stated, your check is also wrong as it requires both numbers to be out of range so if just one is, it doesn't return false.
To make it easier, try to turn the condition around so that both numbers must be in range:
if(!(number1 >= 10 && number1 <=99 && number2 >= 10 && number2 <= 99)) {
return false;
}
Often it might also be easier to read and maintain the code if you'd "name" the conditions:
boolean n1InRange = number1 >= 10 && number1 <=99;
boolean n2InRange = number2 >= 10 && number2 <=99;
if( !(n1InRange && n2InRange) { ... }
//or
if( !n1InRange || !n2InRange ) { ... }
This is my Solution
public static boolean hasSharedDigit(int x, int y){
if( (x < 10 || x > 99) || (y < 10 || y > 99)){
return false;
}
int xFirst = x / 10;
int yFirst = y / 10;
int xLast = x % 10;
int yLast = y % 10;
if((xFirst == yFirst || xLast == yLast) || (xFirst == yLast || xLast == yFirst)){
return true;
} return false;
}

Initializing an int variable before if statement

When compiling i get an Error stating that my variable has not been initialized.
Code :
int number;
if (dotted==true)
{
if (input >= 1 && input <= 21)
{
number = 1;
System.out.print("True");
}
if (input >= 22 && input <= 40)
{
number = 2;
System.out.print("False");
}
if (input >= 41 && input <= 63)
{
number = 3;
System.out.print("False");
}
if (input >= 64 && input <= 82)
{
number = 4;
System.out.print("True");
}
}
else
{
if (input >= 2 && input <= 22)
{
number = 1;
System.out.print("True");
}
if (input >= 23 && input <= 41)
{
number = 2;
System.out.print("False");
}
if (input >= 42 && input <= 64)
{
number = 3;
System.out.print("False");
}
if (input >= 65 && input <= 83)
{
number = 4;
System.out.print("True");
}
}
System.out.print(number); // number is not initialized?
Why is number not initialized?
I put int number = 0;
But then when i print, no matter the value of input it stays at 0?
Love how people downvote this. A student new to java with a question gets downvoted. Nice site
You need to put int number = 0 because you can't be sure whether the IF statement is executed or not. That's a precaution for your code.
Also, if you think about it, if it keeps being 0, it means you're actually not entering into the IF statement.
Try to put that and check if the dotted variable is actually TRUE or not.
Check also your variable input, because it is the one that changes your number variable.
Why is number not initialized?
Simply, because if none of the if statements are executed then the number variable will never get initialised. Hence the variable will not have a value and that's why you get the following error:
When compiling i get an Error stating that my variable has not been
initialized.
Also, remember local variables must be initialized before the method exits.
with that in mind, you must at least give the variable below a default value:
int number = 0;
I put int number = 0; But then when I print, no matter the value of
input it stays at 0?
if that's the case then it means you're never entering into the if statement. So, you might have to consider your if statement expressions again.

Java - AND operator not working

newbie here,
I have two variables which generate random numbers through .Random. I want them keep rolling until both variables generate two different values, simultaneously. Therefore, I'm using while loop with && for this purpose. As I have understood, please correct me if I'm wrong, the line while ((diceRolled1 != 5) && (diceRolled2 != 4)) translates as, keep rolling until the values of diceRolled1 is not equal to 5 AND diceRolled2is not equal to 4. But the program ends if either variable matches its value (diceRolled1 = 5 OR diceRolled2 = 4). This is not what && is supposed to do, right? I have ran the code like 10s of times, but not a single time it generated 5 and 4 at the same time.
I also tried ==on both sides and either side, but in that case the program didn't run at all, nor it gave any error.
Your help will be much appreciated. Thanks
import java.util.Random;
import static java.lang.System.out;
public class DiceRoller {
public static void main(String[] args) {
Random dice1 = new Random();
Random dice2 = new Random(); //Removing this doesn't work either
int diceRolled1 = 0;
int diceRolled2 = 0;
while ((diceRolled1 != 5) && (diceRolled2 != 4)) { //& didn't work either
diceRolled1 = dice1.nextInt(6) + 1;
diceRolled2 = dice2.nextInt(6) + 1;
out.println(diceRolled1 + " " + diceRolled2);
}
out.println("Program ends");
}
}
Your logic is incorrect. The loop will continue as long as both values don't match - as soon as one value matches, the loop exits. We can invert your logic to show this:
while (!(diceRolled1 == 5 || diceRolled2 == 4)) {
which is logically equivalent to what you have.
What you want is this:
while (diceRolled1 != 5 || diceRolled2 != 4) {
which says "Continue while any variable does not have the desired value"
You're getting the logical result you describe, but it wasn't what you expect. Specifically, when either of your conditions evaluates to false the logical and will not evaluate to true. I think you wanted
while (!(diceRolled1 == 5 && diceRolled2 == 4)) {
which is while not dice1 equal to 5 and dice2 equal to 4. And then, using De Morgan's Laws that might also be expressed as
while (diceRolled1 != 5 || diceRolled2 != 4) {
which means loop while dice1 is not equal to 5 or dice2 is not equal to 4.
the while execute the statement untill the condition is true.
In your code the condition is given by (diceRolled1 != 5) && (diceRolled2 != 4).
The && operator require true that all operands be true.
Given this Your loop will end when at least one of the expression will be false.
To finish the program when it generate 5 and 4 you have to use this:
(!(diceRolled1 == 5) && (diceRolled2 == 4))
Yeah,it should be. The program should end if dicerolled is either 5 or 4 because as far as it is not 4 and not 5 it is in while loop. It exits the while loop if only the value is either 4 or 5. So your logic is incorrect. Sorry! :)
Try:
while (!(dicerolled ==4 && dicerolled == 5))

JOptionPane.showInputDialog loop (using do while loop)

I'm trying to ask for an integer between 4 and 10 from the user. If they answer out of that range it will go into a loop. When the user inputs the number correctly the first time it will not break and continues to else statement. If the user inputs the number correctly during the else statement it will properly break.
How can I get it to break if input is correct the first time around?
**I am very much a beginner at java and do apologize if it is something silly i'm missing here.
public int companySize() {
int ansCompany;
do {
ansCompany = Integer.parseInt(JOptionPane.showInputDialog
("Please input the company size"));
if ( ansCompany <= 4 && ansCompany <= 10 ) {
break;
} else {
ansCompany = Integer.parseInt(JOptionPane.showInputDialog
("Please enter a valid company size"));
if ( ansCompany <= 4 && ansCompany <= 10 ) {
break;
} // ends nested if condition
} //ends else
}//ends do
while ( ansCompany < 4 || ansCompany > 10);
return ansCompany;
}// ends public int companySize()
I'm calling it from main as follows:
public static void main(String[] args) {
UserInput getResult = new UserInput();
int company_size = getResult.companySize();
}// ends main
I am not sure why you need two identical dialogs if the user would write the wrong value the first time, since in the end only one value will be returned (ansCompany).
By setting the do-while statement to the break condition (less than 4 or greater than 10) it will loop until the user inputs the correct number.
public int companySize() {
int ansCompany;
do {
ansCompany = Integer.parseInt(JOptionPane.showInputDialog
("Please input the company size"));
} while (ansCompany < 4 || ansCompany > 10);
return ansCompany;
}
while ( ansCompany < 4 || ansCompany > 10); is anything below 3 OR higher than 11
You want while ( ansCompany >= 4 && ansCompany <= 10);
Note: The reason you want this choice ^^^^ is because if the input is greater than > or equal = making >= than means 4 and above. Likewise for less than < or equal = making <= than means anything less than 10
The || means OR. This mean the input must be greater than 4 or less than 10. If the answer is 11, It passes the first condition and therefore passes the if statement. Likewise with a 3, it passes the less than 10 condition.
&& mean AND, and therefore must pass the first condition, AND the second condition.
Your if statements also are wrong in this sense;
if ( ansCompany <= 4 && ansCompany <= 10 ) {
should be
if ( ansCompany >= 4 && ansCompany <= 10 ) {
I would rather use a recursive function:
Version1: In short:
public int companySize() {
final int result = Integer.parseInt(JOptionPane.showInputDialog("Please input the company size"));
return (result >= 4 && result <= 10) ? result : companySize();
}
Version 2: But you also can use static constants
/* don't be afraid of shared constants; sometimes they're very "useful idiots" */
/*public*/ static final int MIN = 4;
/*public*/ static final int MAX = 10;
/*public*/ static final String MESSAGE = "Please input the company size";
public int companySize() {
final int result = Integer.parseInt(JOptionPane.showInputDialog(MESSAGE));
return (result >= MIN && result <= MAX) ? result : companySize();
}
Version 3: And if you want to show an error message:
/* don't be afraid of shared constants; sometimes they're very "useful idiots" */
/*public*/ static final int MIN = 4;
/*public*/ static final int MAX = 10;
/*public*/ static final String MESSAGE = "Please input the company size";
/*protected*/ static final String ERROR_MESSAGE = "Please input a valid company size";
public int companySize() {
final int result = Integer.parseInt(JOptionPane.showInputDialog(MESSAGE));
return (result >= MIN && result <= MAX) ? result : companySize(ERROR_MESSAGE);
}
private int companySize(String errorMessage) {
final int result = Integer.parseInt(JOptionPane.showInputDialog(errorMessage));
return (result >= MIN && result <= MAX) ? result : companySize(ERROR_MESSAGE);
}
and
public static void main(String[] args) {
UserInput getResult = new UserInput();
int company_size = getResult.companySize();
}

Categories

Resources