"If" Statement Will Not Print in Loop - java

My code works, there's is just one problem. The code is meant to be about printing the numbers in between two user inputs. That part of the code works, however if the first number is greater than the second number it is meant to not print and ask again. Everything up to that point works, however if the first number is greater than the second, the console and code just end, and I cannot figure out why? Can you guys help and explain what I am doing wrong? Thanks! Here is my code:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int higherNum, lowerNum;
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
while (higherNum>=lowerNum){
if (lowerNum>higherNum){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. "); // this does not print
}
}
System.out.println(lowerNum++);
}

Your loop only starts if higherNum >= lowerNum, which means your if condition inside the loop will never be true.
To achieve your output, you should do something as following.
while (lowerNum>higherNum ){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. "); // this does not print
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
}
while(lowerNum <= higherNum) {
System.out.println(lowerNum++);
}

I would suggest that you use your if condition first:
if (lowerNum>higherNum){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. ");
} else{
while (higherNum>=lowerNum){
System.out.println(lowerNum++);
}
}
It's happening because if the lowerNum is bigger than the higherNum your while condition would result in false and won't print anything since the error message is inside the while loop.

Your if should be before while. I fixed some other things on the way.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int higherNum = 0, lowerNum = 1;
while(lowerNum>=higherNum){
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
if(lowerNum>=higherNum){
System.out.println("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. ");
} else {
while(lowerNum<higherNum-1){
System.out.println(++lowerNum);
}
}
}
}

You can give the number inputs with a method for restarting the process. Recursive option would be helpful for that issue.
public void TakeNumbers(){
Scanner reader = new Scanner(System.in);
int higherNum, lowerNum;
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
if (lowerNum>higherNum){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. ");
TakeNumbers();
System.out.println(lowerNum++);
}
public static void main(String[] args) {
TakeNumbers();
}

Related

Checking length of a String and using do-while in Java

I want to create a program where you enter a string and it checks if the length is 9 or not. If it is, it gives a message that it is okay. If not, it will give a message that is not, and prompt the user to enter the string again. While running it, I always get that is wrong. Where am I going wrong?
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner Secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String Sec = Secnum.nextLine();
do{
if (Sec.length()!= 9);
System.out.println("Wrong lenght Sec,enter again");
Secnum.nextLine();
}while (Sec.length() == 9);
System.out.println("Sec lenght okay");
}
}
You want to request a new value as long as the length is NOT 9.
So your loop should have that as condition. Further your if is incorrect. If in Java needs curly braces else it will effect the next statement only. A statement can be only a semi-colon as well. So your if-statement is completely useless.
To make the code even more compact you can take out the if and swap the do-while loop. That will only run if the condition is true and not once in the beginning no matter the condition.
A code that should work better:
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String sec = secnum.nextLine();
while (sec.length() != 9) {
System.out.println("Wrong lenght Sec,enter again");
secnum.nextLine();
}
System.out.println("Sec lenght okay");
}
}
On a side note: Use lowercase variable names. That is the better code-style :)
You are terminating the if statement.
if (Sec.length()!= 9);
So, the next print always executes irrespective of it being true or not.
Put the logic for failure inside an if block.
if (Sec.length()!= 9) {
// Print failure message
// Other logic
}

No output from program to find all palindrome numbers within a given range

Create a java program to find and print all palindrome numbers within b and a
such that a<3000, b<3000and b<a.
My approach:-
import java.util.*;
class PalinDrome_Within_A_Range_Of_Two_Numbers{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
j=(int)(Math.log10(i) + 1);
e=0;
f=0;
d=i;
for(int k=1;k<=j;k++){
f=i%10;
f=(int)(f*(Math.pow(10,(j-k))));
i=(i-(i%10))/10;
e=e+f;
}
if(e==d){
c=c+1;
System.out.println("The "+c+"th Palindrome number between "+b+" and "+a+" is "+d);
}
else{
break;
}
}
}
}
In this program, nothing appears in the output after giving the two integers.
The reason is that the first number, if it is not a palindrome, will end the loop at the else break; statement. To fix the problem, you should also not manipulate i within its loop, but rather a copy of it.
You may think about debugging. Shows you the point of failure faster than Stackoverflow.
Are you absolutely sour you enter uper limit before entering the lower limit because I by intuition added lower limit first and it did not work any way here is a simpler soultion if you want
public class PalinDrome_Within_A_Range_Of_Two_Numbers {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
String num = String.valueOf(i);
String reversNum = getReversStr(num);
if(num.equals(reversNum)){
System.out.println(num);
}
}
}
private static String getReversStr(String num) {
char[] chars = num.toCharArray();
char[] revers = new char[chars.length];
for(int i = chars.length;i>0;i--)
revers[chars.length-i]=chars[i-1];
return new String(revers);
}
}
Others already suggested to use a debugger. That makes sense because your code is quite complicated. (By the way, you should keep the scope of your variables as small as possible to make your code more readable. It makes no sense to declare and initialize a variable outside a loop when it is used only inside the loop body.)
A better approach would be to simplify your code. You could split it into multiple functions and give each of these a meaningful name.
Or you could use a completely different approach. Being a palindrome is not so much a property of the number itself but of its string representation. So why not base the whole algorithm on strings:
for (int i = b; i <= a; i++) {
String num = String.valueOf(i);
String reverse = new StringBuilder(num).reverse().toString();
if (num.equals(reverse)) {
System.out.println(i);
}
}
I see two issues with your code (no guarantee that they are the only two, but solving them should get you a step further at the least).
You are using i as control variable in your outer loop, and then you are modifying i inside your inner loop (i=(i-(i%10))/10;). Since you are taking a copy of i into d anyway, there is a simple fix: do the modification on d instead of on i.
The break; statement in you else part will break out of the outer loop if the first number tried (b) is not a palindrome. I think you can just delete the else part.
I tried entering 102 as upper limit and 99 as lower. Your program correctly prints The 1th Palindrome number between 99 and 102 is 99, but then because i has been modified goes into an infinite loop. So you are on the way.
I agree with what others have said about breaking your code up in less comlex methods. This will also allow unit testing each method, which will help to locate bugs. Better variable names will help understanding the code, not least when you ask others to take a look. Finally, don’t declare a variable until you need it, this will also help readability.

Is there another way to use hasNextInt() in Java without putting everything in the if-statement?

My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);

Retrieves and display endless amount of numbers in an array

I"m trying to make a program that retrieves an endless amount of numbers that user inputs until the user quits and display the numbers .Here is the code I have so far.After entering the first and second number it shows an exception at the line array1[i]=s1
import java.util.Scanner;
public class Program_2 {
public static void main(String[] args) {
int a=1,i;
Scanner sn = new Scanner(System.in);
String[] array1= new String[a];
for(i=0;i<a;i++)
{
System.out.println("Enter Value Number "+ (i+1));
System.out.println("Press Q or q to Exit");
String s1=sn.next();
if(s1.equalsIgnoreCase("q"))
{
for(i=0;i<a;i++)
{
System.out.println("Value of Number "+(i+1)+" is "+ array1[i]);
}
a=0;
}
else
{
array1[i]=s1;
a=(i+2);
}
}
}
}
Your array is of size 1 (a is 1 at the beginning of your code).
The first input works because i is 0 and array1[0] exists. The second input crashes because array1[1] does not exist.
You need to increase your array. That can be done by copying the array into a larger one and using the result of the copy, but that is clumsy.
Better way to do it is to use an ArrayList instead of a simple array and you do not have to worry about the size as it is managed automatically.
For one, a is only incremented when they press q, when you go to the else statement. So the the for loop is going to end after a couple of iterations.
You also set a to 0 in the inside for loop, making sure it won't run more.
Also, your quit code doesn't quit.

Printing binary digits of a number

Need to write a java program from pseudo code, I've got a bit of code written, its not working and I'm not sure if i've done it right or not as I simply tried to follow the pseudo code -
Read i
While i > 0
Print the remainder i % 2
Set i to i / 2
import java.util.Scanner;
import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
int i = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
while (!scan.hasNextInt()) // while non-integers are present
{
scan.next();
System.out.println ("Bad input. Enter an integer.");
}
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
}
}
Frankly speaking, you didn't(Ah missed it earlier) exactly followed the pseudo-code. The pseudo code tells you to read i, whereas you are reading input. That's one problem.
Second problem is that, you should read the input outside the while loop where you are doing the processing with the input. That is the 2nd thing you didn't followed.
Currently your while loop is: -
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
This is read input from user on every iteration which you don't want.
So, you need to modify your code a little bit: -
int i = scan.nextInt(); // Read input outside the while loop
while (i>0) // while greater than 0
{
System.out.println (i%2);
i = i/2; // You don't need a bracket here
}
How about:
System.out.println(Integer.toBinaryString(i));
The pseudo code reads first (outside the loop), but in your code you read second (inside the loop)

Categories