I am having a problem with my while loop. It is compiling but it isn't entering while loop and it skips to next condition.
public class Tr {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = "";
while(name.length() > 1) {
System.out.print("Enter name : ");
name = in.nextLine( );
if(name.length() > 1) {
System.out.println("It needs to be greater than 1");
}
}
}
}
That's because the name has 0 length and hence, the control never enters while. You need to use do..while loop so that it executes at least once, e.g.:
do{
System.out.print("Enter name : ");
name = in.nextLine( );
if(name.length() <= 1){
System.out.println("It needs to be greater than 1");
}
}while(name.length() <= 1);
It appears that the logic you want is to prompt the user for a name, and keep prompting until a name with length greater than one is entered. A do loop would seem to fit well here:
Scanner in = new Scanner(System.in);
String name;
do {
System.out.print("Enter name with length > 1: ");
name = in.nextLine();
// you can print an optional feedback message
if (name.length() <= 1) {
System.out.println("length needs to be greater than 1");
}
} while (name.length() <= 1);
Your variable name gets initialized to name = "";, so name.length() == 0;.
Your while condition checks whether the length greater than 1, and it isn't so it skips.
Because name.length() always returns 0 so your condition won't ever be true.
(name.length() < 1)
change this condition in our while and if conditions.
You have defined an empty string called name and the condition for your while loop condition checks if the length of name is greater than 1 or not.
Related
public class Test1 {
public static void main(String[] args) {
System.out.println("Give me a word: ");
Scanner console = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<>();
boolean found = true;
while (console.hasNextLine() && found) {
String line = console.nextLine();
if (line.equals("")) {
found = false;
} else {
arr.add(line);
}
}
System.out.println("You said: ");
for (int index = 0; index < arr.size(); index++) {
System.out.println(arr.get(index));
}
}
}
I'd like to print what user typed in whenever the user types enter twice, however this requires three enters to be inputted for some reason. When I remove the console.hasNextLine statement in while loop's condition, it works perfectly fine. Why is this the case?
console.hasNextLine() blocks application flow and waits for input to be received.
1st enter - word is found and found remains == true
2nd enter - word is not found and found is set to == false
3rd enter - is required because your booleans are evaluated in order which they are arranged. so first it'll call console.hasNextLine() and allow user to provide input. THEN it'll check if found == true/false which would == false and would break out of the loop.
an easy solution would be to rearrange your conditions to be
found && console.hasNextLine()
I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```
Firstly - I thank anyone who takes the time to actually look at this since I feel like it's a rather annoying request.
I just completed a large challenge at the end of a series of Java 101 videos. The challenge is to design a guest list method ( as in for a restaurant or a party ) and some features along with it. This is really the first time I've written anything with multiple methods.
As the final step in this challenge, I need to design a method that allows the user to insert a new guest at a certain position while not removing any other guests. In other words, inserting a new guest and shifting the remaining guests downwards by a single index.
The issue I have is that the new guest is always inserted not only for the position I want, but also the position one after. It inserts itself twice and ends up over-writing the previous guest in the process.
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
public class GuestList_Edited {
public static void main(String[] args) {
// Setup for array, setup for scanner
String[] guests = new String[11];
Scanner scanner = new Scanner(System.in);
// A method to put these here so we don't always have to add guests. This method automatically inserts five guests into the guest list.
InsertNames(guests);
// Do-while loop to make sure that this menu screen shows up every time asking us what we want to do.
// It also makes certain that the menu shows up when we initially run the program.
do {
displayMenu(guests);
// This must remain in main for the rest of the program to reference it.
int option = getOption();
// If loop that will allow people to add guests
if (option == 1) {
addGuest(guests);
} else if (option == 2) {
RemoveGuest(guests);
} else if (option == 3) {
RenameGuest(guests);
} else if (option == 4) {
insertGuest(guests);
} else if (option == 5) {
System.out.println("Exiting...");
break;
}
} while (true);
}
// This displays the starting menu
public static void displayMenu(String SentArr[]) {
System.out.println("-------------");
System.out.println(" - Guests & Menu - ");
System.out.println();
GuestsMethod(SentArr); // Makes all null values equal to --
System.out.println();
System.out.println("1 - Add Guest");
System.out.println("2 - Remove Guest");
System.out.println("3 - Rename guest");
System.out.println("4 - Insert new guest at certain position");
System.out.println("5 - Exit");
System.out.println();
}
// This prints all the guests on the guest list and also adjusts the guest list when a guest is removed
public static void GuestsMethod(String RecievedArr[]) {
// If loop which prints out all guests on the list.
// "Null" will be printed out for all empty slots.
for (int i = 0; i < RecievedArr.length - 1; i++) {
// Make all null values and values after the first null value shift up in the array.
if (RecievedArr[i] == null) {
RecievedArr[i] = RecievedArr[i + 1];
RecievedArr[i + 1] = null;
}
// Make all null's equal to a string value.
if (RecievedArr[i] == null) {
RecievedArr[i] = " ";
}
// If values are not equal to a blank string value, assign a number.
if (RecievedArr[i] != " ") {
System.out.println((i + 1) + ". " + RecievedArr[i]);
}
// If the first value is a blank string value, then print the provided line.
if (RecievedArr[0] == " ") {
System.out.println("The guest list is empty.");
break;
}
}
}
// I've really got no idea what this does or why I need a method but the course I'm taking said to create a method for this.
// It gets the desired option from the user, as in to add a guest, remove a guest, etc.
static int getOption() {
Scanner scanner = new Scanner(System.in);
System.out.print("Option: ");
int Option = scanner.nextInt();
return Option;
}
// Allows users to add guests
public static String[] addGuest(String AddArr[]) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < AddArr.length; i++) {
// The below if statement allows the program to only ask for a name when a given space is "null", meaning empty.
if (AddArr[i] == " ") {
// so the loop runs until it hits a null value.
System.out.print("Name: ");
AddArr[i] = scanner.nextLine();
// Then that same value which was null will be replaced by the user's input
break;
}
}
return AddArr;
}
public static String[] RemoveGuest(String RemoveArr[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RemoveArr.length; i++) {
if (RemoveArr[number] != null) {
RemoveArr[number] = null;
break;
}
}
return RemoveArr;
}
// This inserts names into the array so we don't have to add guests everytime.
public static String[] InsertNames(String InsertNames[]) {
InsertNames[0] = "Jacob";
InsertNames[1] = "Edward";
InsertNames[2] = "Rose";
InsertNames[3] = "Molly";
InsertNames[4] = "Christopher";
// guests[5] = "Daniel";
// guests[6] = "Timblomothy";
// guests[7] = "Sablantha";
// guests[8] = "Tagranthra";
return InsertNames;
}
public static String[] RenameGuest(String RenamedGuests[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RenamedGuests.length; i++) {
if (RenamedGuests[number] != null) {
RenamedGuests[number] = null;
System.out.println("What would you like the guest's name to be?");
String NewName = scanner.next();
RenamedGuests[number] = NewName;
break;
}
}
return RenamedGuests;
}
// The final method which I am struggling with.
public static String[] insertGuest(String NewPositionArray[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
scanner.nextLine();
if (num >= 1 && num <= 10 && NewPositionArray[num - 1] != null)
System.out.print("Name: ");
String name = scanner.nextLine();
for (int i = 10; i > num - 1; i--) {
NewPositionArray[i] = NewPositionArray[i - 1];
NewPositionArray[num - 1] = name;
}
if (num < 0 || num > 10) {
System.out.println("\nError: There is no guest with that number.");
}
return NewPositionArray;
}
}
Once again, thanks. I realize I've probably done 1000 things wrong here. I appreciate your consideration.
I recommend you to declare ArrayList object instead of the normal array declaration; to avoid heavy work on the code where you can add an element into the ArrayList object with predefined add(int position, an element with your data type) method in a specific position and the ArrayList automatically will shift the rest elements to the right of it.
and for several reasons.
for more info about ArrayList in Java, please look at: -
Array vs ArrayList in Java
Which is faster amongst an Array and an ArrayList?
Here an example of add() method; which inserts the element in a specific position: -
Java.util.ArrayList.add() Method
I want my program to do the certain code only if the actors variable is <=5 && >0
else I want to go back and ask different question again:
System.out.println("\nEnter actors number(max.5): ");
int actorsNumber = scanner.nextInt();
scanner.nextLine();
if (actorsNumber <= 5 && actorsnumber>0) {
for (int i = 1; i <= actorsNumber; i++) {
System.out.println("\nEnter name and surname of the " + i + " actor: ");
String[] parts2 = scanner.nextLine().split("\\s+");
String actName = parts2[0];
String actSurname = parts2[1];
actorName.add(actName);
actorSurname.add(actSurname);
}
}
So when the condition is false for example actors number = 7 then I want to tell the user: "Enter the valid actors number(1-5)" and do the for loop again if the actorsnumber is 1-5 instead ask again "Enter the valid actors number(1-5)"
You need to ask user to enter number in a loop. The condition of the loop will be the condition of your if. Then after exiting the loop (which means user enter a correct number), enter your for loop.
This will look like that :
int actorsNumber = -1; //force a wrong value at the beginning
while(actorsNumber < 1 || actorsNumber > 5) {
//Ask user to enter a number between 1 and 5
//store this number in actorsNumber
}
//As we exited the while-loop, actorsNumber is between 1 and 5
//Put your for-loop here
while(!scanner.nextLine().equals("quit")) {
if (actorsNumber <= 5 && actorsnumber>0) {
for (int i = 1; i <= actorsNumber; i++) {
System.out.println("\nEnter name and surname of the " + i + " actor: ");
String[] parts2 = scanner.nextLine().split("\\s+");
String actName = parts2[0];
String actSurname = parts2[1];
actorName.add(actName);
actorSurname.add(actSurname);
}
}
}
Or something like that, point is, use a while loop on the scanner.
As #apexlol stated, your code should be in a loop. However, do-while loop is more convenient than while loop since that way, the loop executes at least once no matter what.
I want to write a loop that prompts the user to input their first middle and last name, I then want to validate that input by searching for the white spaces in between each name.
Example: First Middle Last
What I'm looking for is some thing like the following.
Pseudo Code: if name contains 2 white spaces and their are less than 3 white space in name the operation has been successful other wise tell the user to re-input their first middle and last name.
How can I go about doing this?
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isName = false;
String name = "";
int x = name.length();
Scanner input = new Scanner(System.in);
while(!isName) // Probably better to remove the while loop entirely
{
System.out.print("Please input your 'First Middle Last' name: ");
name = input.nextLine();
name.trim(); // To remove any leading or trailing white spaces
for(int i = 0; i < x; i++)
{
if(name.lastIndexOf(' ', i) == 2 && name.lastIndexOf(' ', i) < 3)
{
isName = true;
break;
}
else
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
name = name.trim();
System.out.print("\nInvalid input");
}
}
}
}
The above produces an infinite loop and logically I understand why.
You could split your String on one or more white space characters and check that you get three elements. Something like,
boolean isName = false;
String name = "";
Scanner input = new Scanner(System.in);
while (!isName) {
System.out.print("Please input your 'First Middle Last' name: ");
name = input.nextLine();
isName = (name.trim().split("\\s+").length == 3);
if (!isName) {
System.out.print("\nEnter your name as 'First Middle Last': ");
}
}
Here is the problem (infinite loop):
for(int i = 0; i < x; i++)
x is initialized to 0 because name.length() is 0 initially. Since the condition i<x is never satisfied, it never enters the for loop and the while loops goes on for ever.
Right before the for loop, you need to do x = name.length(). Also, as others have suggested you need to enclose the statements inside {} for the else part.
As per this link you can count white spaces with:
int numOfSpaces = s.length() - s.replaceAll(" ", "").length();
With this you can tell if you have at least 2 spaces. The link also goes over different methods of counting how many white spaces exist in a given String.
Cheers!