Checking length of a String and using do-while in Java - 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
}

Related

"If" Statement Will Not Print in Loop

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();
}

How to ask te user and depending on his response run all the code again?

I'm a newbie in Java. I started these days and I'm practicing the catch and try exception. I have this code below which solve an operation between to numbers and I'd like to know what can I do, if for example I want that the user, once he makes an operation and get his result, that this has the possibility to make another operation. something like comes up a question asking if he wants to realize another problem and the code run again from the beginning.
package justpractice;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner Operation = new Scanner(System.in);
int x=1;
while(x==1){
try{
System.out.println("Insert numerator");
int n1 = Operation.nextInt();
System.out.println("Insert denominator");
int n2=Operation.nextInt();
double division = n1/n2;
System.out.println(division);
x=2;
}
catch(Exception e){
System.out.println("Insert a valid value");
}
}
}
}
You can do, for example, adding an if statement with a
System.out.println("Do you want to recalculate ? (1/0 Yes/No)");
Operation.nextInt();
then if the input is 1, keep x = 1, else do x = 2.
Try this code amendment;
package justpractice;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner Operation = new Scanner(System.in);
//better practice
while(true){
try{
System.out.println("Insert numerator");
int n1 = Operation.nextInt();
System.out.println("Insert denominator");
int n2=Operation.nextInt();
double division = n1/n2;
System.out.println(division);
System.out.println("Continue? (y/n)");
String response = Operation.nextLine();
if (response.equals("n")){
break;
}
}
catch(Exception e){
System.out.println("Insert a valid value");
}
}
}
}
To allow your user to calculate division again, you could use a do-while loop. With this loop you can execute the code inside once, ask the user if they would like to calculate again, and repeat the code if they do.
An outline of your code with the loop would something like this:
...
boolean again = true;
do { //Main loop
try {
... //Your division code
... //Put code to ask the user if they want to calculate again here
} catch(Exception e) {
...
}
} while(again == true); //Repeat if the user wants to continue
To get input on if the user wants to calculate again, I recommend using another do-while loop with your Scanner. This loop will allow you to repeat the code when the answer is invalid. In this case, when it's not "y" or "n".
String input;
do {
System.out.println("Would you like to continue? (y/n)");
input = operation.next();
} while(!input.equalsIgnoreCase("y") && !input.equalsIgnoreCase("n"));
After you have got the user's input, you still need to terminate the loop if they said "n". To do this you could use an if statement.
if(input.equalsIgnoreCase("n")) {
again = false; //Terminate the main loop
operation.close(); //Prevent any resource leaks with your Scanner
}
There is no need to check if the user input "y" as again is set to true by default.
Side Note: Variables should always be camelCase. Look at the Java Naming Conventions to learn more about naming things in Java.
EDIT:
The reason the console is repeatedly logging that you entered a non-number even though you entered it once, I'm not exactly sure. I think it's because the call to nextInt() never finishes because of the InputMismatchException being thrown, causing the next call to nextInt() (After the do-while repeats) to think that the letter/symbol you just entered is the one you want to process, repeating the exception over and over again.
To solve this, add this line into your catch block:
if(operation.hasNext()) operation.next();
This will call next() and complete the process of marking the letter/symbol you just entered as already processed, then repeat the do-while loop as normal.

Make Java Program Loop until x is entered?

I want to make my program loop until the user types in x instead of a number. I tried using a while statement but I do not know how to use it with multiple variables. Here is my code
public static void main(String[] args)
{
int denominatorOne = 1, numeratorOne = 1;
System.out.println("Welcome, type an \"x\" at any point to exit the program");
while (numeratorOne !=x)
{
Scanner in = new Scanner(System.in);
//Prompt the user for fraction one
System.out.print("Enter the first numerator (top number): ");
numeratorOne = in.nextInt();
System.out.print("Enter the first denominator (bottom number): ");
denominatorOne = in.nextInt();
}
}
The exact phrasing from my assignment is The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)
First off, 'x' isn't a number and won't be accepted by nextInt or a comparison to 'x', you should trying checking to see if it has next int (in.hasNextInt()) and process depending. Besides the point, you can easily test two variables in a while loop. Assuming you set up the variables right to be chars:
do {
// scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))
what you need to do is have a bool value that holds the loop and when have a if statement check for the keydown event in the loop
bool looping = true
while ( looping == true)
{
if (x button was pressed == true)
{looping = false
}
}
try changing it to
while(!numeratorOne.equals("x")){...}
You can just call the method over again in this case main();.
What I suggest however is to create a new method, in the method just checking the users input returning the input as a string. Then you can check the string in your main method, and if that's not the string you wanted then recall the method. Here's an example, please note I didn't use an IDE for this.
public String getMessage(){
Scanner input = System.in();
return input;
}
public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}
public static void main(String[] args){
checkMessage();
}

While Loop executing one last time when condition is set to false

Task: To check that if a user input string has the same first and last character. If yes or no, output to the screen, if the user enters "done", the loop is exited.
Issue: While loop executes when condition is false
What I've tried: Using different types of loops, doing a loop within the loop to revalidate the code and all together giving up!
import java.util.*;
public class lab_15 {
public static void main(String args[]) {
String userInput = "";
String done = "done";
while (!userInput.equalsIgnoreCase(done))
{
int length;
Scanner sc = new Scanner(System.in);
userInput = sc.next();
length = (int)userInput.length();
if (userInput.charAt(0) == userInput.charAt(userInput.length()-1)) {
System.out.println("The first character equals the second character.");
}
else {
System.out.println("The first and second characters are different.");
}
}
// EXIT LOOP
System.out.println("Thank you for using this software!");
}
}
Inputs
+ bradley
+ hannah
+ done
I am still new to the site and have referred to the t's & c's regarding posts. Please do not negative if you find the question to not be challenging. I am new to programming and hope to progress.
Thank you!!!
This is because you change your userInput immediately once entering the loop. The condition is only checked when you reach the top of the loop, so if you invalidate the condition halfway through, it will continue executing until you reach the top.
The solution is to refactor so that the very last thing that happens is changing your userInput so that the condition is check immediately after the value is changed. (I would also pull the scanner instantiation out of the loop.)
Alternatively you could check your condition inside of the while loop and call break if the userInput has changed to match the terminating condition. The break keyword will force the logic to exit the loop immediately, without evaluating the condition again.

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