I try to check if characters in a firstname String contain at least 1 digit, if yes ask to the user to input it again and then going back to the loop and check again but with a GoTo break it only works the first time and won't loop it again. Oh and I do this from a method with a String array of more than only a first name in it. Isn't the break GoTo supposed to bring me back to my label and then do the loop over again looking for a digit?
public static void main(String[] args) {
infoInputGathering();
}
public static String[] infoInputGathering(){
String[] infos = new String[3]; // Declaration of the infos String array
boolean isStringOnly;
char[] characterChecker;
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
// Asking the user to input their first name and stores it in a String Array info[0]
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
firstname:
for (int c = 0 ; c<=characterChecker.length ; ++c ) {
if (Character.isDigit(characterChecker[c])) {
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
Break firstname;
}
}
Final Full Code I came up with with Ali's help on this part
import java.util.Scanner;
import java.util.ArrayList;
public class InfiniteInfoGatheringUntilStop {
public static void main(String[] args) {
int iterationsCounter = 0; // Declares/Initiate a counter for the loops
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
ArrayList<String> names = new ArrayList<String>(); // Creates an ArrayList for the names inputs
ArrayList<String> birth = new ArrayList<String>(); // Creates an ArrayList for the date of birth inputs
ArrayList<String> gpa = new ArrayList<String>(); // Creates an ArrayList for the GPA inputs
while(true){ // Always true loop unless break out on if conditions
System.out.print("Enter your name: ");
names.add(input.next());
//Code to check if there are numerical character in the String of the listArray inputted
char[] characterChecker = names.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
int c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as numerical
if(Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
names.set(iterationsCounter,input.next());
characterChecker = names.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){
break;
}
}
if(names.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
break;
}
System.out.print("Enter your date of birth in this format AAAAmmdd: ");
birth.add(input.next());
characterChecker = birth.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 8){ // Checks for a maximum length of 8 characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checkes if there are letters in the characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(birth.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
break;
}
System.out.print("Enter your GPA in 0.0 format: ");
gpa.add(input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 3){ // Checkes for a maximum length of 8 characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA please: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checks if there are digits in the characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(gpa.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
gpa.remove(iterationsCounter);
break;
}
iterationsCounter++; // Incrementes the counter if a full loop is done
}
// Prints the results
System.out.println("Number of valid inputs before you got exhausted: " + iterationsCounter);
System.out.println("====================================================================================");
//A loop to print the content of the 3 ListArrays
for(int arrayLoc = 0; arrayLoc < iterationsCounter; arrayLoc++){
System.out.println((arrayLoc+1) + "-\t" + names.get(arrayLoc) +
"\t\t" + birth.get(arrayLoc) +
"\t\t" + gpa.get(arrayLoc));
}
}
}
You can write your code with while loop like this:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] infos = new String[3];
char[] characterChecker;
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
int c = 0;
while(true){
if (Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
c = 0;
}
else
c++;
if(c == characterChecker.length)
break;
}
System.out.println("Correct Name");
}
}
If c is equal to characterChecker.length, ie in the name, there is no number, then it is correct and we break loop and print Correct Name.
Related
So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out
I am writing my very first java program, I finally got it all written but on the assignment I need to add a function (other than main). My program counts the number of letter in first name, so I was thinking maybe I could add a function that reads how many letters are uppercase? Any ideas?
public class NameLetters{
public static void main(String []args){
Scanner in = new Scanner(System.in);
String firstName; //Asks for the users first name
int count=0; //Count the letters passing through loop
System.out.print("Hello, this program will ask for your first name and then output the number of letters in your name.");
System.out.print("Please enter your first name:");
String firstName = input.NextLine();
for (int i=0; i<firstName.length(); i++) {
if (firstName.charAt(i) != ' ')
Count ++;
}
system.out.print("There are "+Count+" s in the first name "+firstName+" , Thank you for participating. Goodbye!");
}
}
String s = "NaMe";
int upper = 0;
int lower = 0;
for(int i = 0; i<s.length();i++ ) {
int charASCII= (int)s.charAt(i);
if (charASCII <91 && charASCII > 64){
upper ++;
}
if (charASCII <123 && charASCII > 96){
lower ++;
}
}
System.out.print("Given name string contains "+upper+ " uppercase letters & "+lower + " lowercase letters");
public static void main (String[] args)
{
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in " + sentence);
System.out.print("Continue? ");
String decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
}
I want the user to input either "yes" or "no" at the end of the loop, then I want that input to determine whether or not the program will loop again. As it stands right now, the the last line of my code isn't working. I've looked around and I'm not sure what I should do to fix this.
You need to declare your variable decide outside the loop and initialize inside:
String decide;
do {
//do something ...
decide = keyboard.nextLine();
} while (decide.equals("yes"));
You should use keyboard.next() to read a String instead of keyboard.nextLine()
next() only reads a word, nextLine() reads the whole line including Enter so it will never be equal to "yes"
You must declare declare the string describe outside of the do/while loop, otherwise it is a local variable of the do/while loop, and cannot be accessed by the do testing portion. Simply using
public static void main(String[] args) {
String decide;
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in "
+ sentence);
System.out.print("Continue? ");
decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
will solve your problem.
You has to define your variable decide outside of the loop:
String decide = null
do {
....
decide = keyboard.nextLine();
} while (decide.equals("yes"));
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}
I am trying to make some kind of 'Evil Hangman game' (nifty Stanford CS exercises). The purpose of the game is to 'cheat' by removing as many possible word solutions as possible so the user cannot guess before the very end.
I have made a loop (below) which seems to remove many of the words possible words but for some reason it does not remove all of them. The input is a dictionary.txt file which contains about 120K words.
When I 'guess' the letter "a" it will take away roughly 60-70% of the words with "a" in them (estimate based on comparisons between the output with the first couple of words in the txt file)
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
I am aware that my code is a bit messy at this point, I am trying to improve everything about my programming so all feedback is greatly appreciated! I have the feeling that I am including stuff that does not have to be there and so on.
I will post the whole code below in case that helps:
import java.util.*;
import java.lang.*;
import java.io.*;
public class EvilHangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner( System.in );
// introduction and prompting the user for word length
System.out.println("Welcome to Hangman. Let's play! ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
while(wordLength < 0 || wordLength > 26)
{
System.out.println("This is not a valid word length. ");
System.out.println("Please enter the desired word length: ");
wordLength = keyboard.nextInt();
}
// prompt the user for number of guesses
System.out.println("How many guesses do you want to have? ");
guessNumber = keyboard.nextInt();
while(guessNumber < 0)
{
System.out.println("Number of guesses has to be a postive integer. ");
System.out.println("Please enter the desired number of guesses: ");
guessNumber = keyboard.nextInt();
}
// count the number of words with the specified length
/* int wordCount = 0;
String word = null;
while ( textScan.hasNext() )
{
word = textScan.next();
if (word.length() == wordLength)
{
wordCount++;
}
}
*/
// prompts the user whether he/she wants a running count of word length - using next() instead of nextLine() to clear buffer
/* System.out.println("Do you want a running total of number of words remaining? ");
String runningTotal = keyboard.next();
if (runningTotal.equalsIgnoreCase("yes"))
System.out.println("Words with that length: " + wordCount);
*/
// create a list (array) of all the words that matches the input length
String word = null;
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while ( textScan.hasNext() )
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while ( textScan1.hasNext() )
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
System.out.println(wordList);
Finally figured out it had to do with the scanner. It had to be initiated inside the loop
for(int i = 1; i <= guessNumber; i++)
{
Scanner textScan2 = new Scanner(file1);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
//System.out.print(guess);
while ( textScan2.hasNext() )
{
String word1 = textScan2.next();
if (wordLength != word1.length() || (word1.contains(guess)))
{
wordList.remove(word1);
}
}
}