I would like to replace a parts of string with another string - java

I am just starting and I have created parts of my code, part a finds the int location of the letter(or phrase)that the user is looking for in the Master string(which is line in the code). Part b counts how many times the letter(or phrase appears). In the next part(WITH OUT CREATING A NEW METHOD) I want if s(what the user is looking) is a "_" to replace them with something else like "-" for instance, and then print it out.
here is my code:
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
public class Main
{
//my code acomplishes the goal but it dose not do it the way you are asking for, sorry:(
public static String line; // The line to format
public static void main(String [] arrrgs)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a master String:");
String line = input.nextLine();
System.out.println("Enter a letter to look for:");
String s = input.nextLine();
System.out.println("Enter a starting location:");
int begin = input.nextInt();
//part a
int loc = begin;
while (loc != line.length()){
loc++;
if (loc != line.length()){
if (s.matches(line.substring(loc, loc + 1))){
System.out.println(s + " appears at " + (loc + 1));//prints location of strin except for first one
}
}
}
int oomf = 1;
if(s.matches(line.substring(0, 1)))//looks at first letter
System.out.println(oomf); //prints if nesasary
//part b
int count = 0;
int timer = begin;
while (timer != line.length()){
timer++;
if (timer != line.length()){
if (s.matches(line.substring(timer, timer + 1))){
count++;
}
}
}
System.out.println(s +"apears " + count + " times.");
}
}

As you see from the comments there is JAVA API to manipulate strings.
Here you are an example how to do it.
public static void main(String[] args) {
String testString = "Hello _ World _";
// Replace with Java API:
System.out.println(testString.replace('_', '-'));
// Replace using own naive code:
String newString = "";
for(int i = 0; i < testString.length(); i++) {
if(testString.charAt(i) == '_') {
newString += "-";
} else {
newString += testString.charAt(i);
}
}
System.out.println(newString);
}
You should be able to adopt this to your program.
Please note that in java all strings are immutable. That means, that you can't change an string once it is created. So you have to create new strings with your changes.
This is why you have to work with the return value of replace(). Your original String will remain the same.

Related

How to remove one charachter from a string

With the scanner I want to read the index of a char and then remove it from the string. There is only one problem: If the char comes multiple times in the string, .replace() removes all of them.
For example I want to get the index of first 't' from the String "Texty text" and then remove only that 't'. Then I want to get index of second 't' and then remove it.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String text = "Texty text";
Scanner sc = new Scanner(System.in);
int f = 0;
int x = 0;
while(f<1){
char c = sc.next().charAt(0);
for(int i = 0; i<text.length();i++){
if(text.charAt(i)==c){
System.out.println(x);
x++;
}
else{
x++;
}
}
}
System.out.println(text);
}
}
You could use replaceFirst:
System.out.println(text.replaceFirst("t", ""));
Probably you are looking for something like the following:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "Texty text";
String copy = text;
Scanner sc = new Scanner(System.in);
while (true) {
text = copy;
System.out.print("Enter a character from '" + text + "': ");
char c = sc.next().charAt(0);
for (int i = 0; i < text.length(); i++) {
if (Character.toUpperCase(text.charAt(i)) == Character.toUpperCase(c)) {
System.out.println(c + " was found at " + i);
text = text.substring(0, i) + "%" + text.substring(i + 1);
System.out.println("After replacing " + c + " with % at " + i + ": " + text);
}
}
}
}
}
A sample run:
Enter a character from 'Texty text': x
x was found at 2
After replacing x with % at 2: Te%ty text
x was found at 8
After replacing x with % at 8: Te%ty te%t
Enter a character from 'Texty text': t
t was found at 0
After replacing t with % at 0: %exty text
t was found at 3
After replacing t with % at 3: %ex%y text
t was found at 6
After replacing t with % at 6: %ex%y %ext
t was found at 9
After replacing t with % at 9: %ex%y %ex%
Enter a character from 'Texty text':
Try using txt.substring(x,y)
x = usually 0 , but x is first start index
y = this is what you want to delete for example for the last word of string write this code:
txt.substring(0, txt.length() - 1)
Since you are specifying indices, it is possible that you may want to replace the second of a particular character. This does just that by ignoring the ones before it. This returns an Optional<String> to encase the result. Exceptions are thrown for appropriate situations.
public static void main(String[] args) {
// Replace the first i
Optional<String> opt = replace("This is a testi", 1, "i", "z");
// Replace the second i (and so on).
System.out.println(opt.get());
opt = replace("This is a testi", 2, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 3, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 4, "i", "z");
System.out.println(opt.get());
}
public static Optional<String> replace(String str, int occurrence, String find, String repl) {
if (occurrence == 0) {
throw new IllegalArgumentException("occurrence <= 0");
}
int i = -1;
String strCopy = str;
while (occurrence-- > 0) {
i = str.indexOf(find, i+1);
if (i < 0) {
throw new IllegalStateException("insufficient occurrences of '" + find + "'");
}
}
str = str.substring(0,i);
return Optional.of(str + strCopy.substring(i).replaceFirst(find, repl));
}

Changing the value of a field String variable

I'm currently working on a version of hangman through java. I've recently been stumped by a problem that I can't seem to solve.
I have an array easyDifficulty and a String hiddenWord. I want to make it so that every time the game starts, my method randomWord() will choose a random word from array easyDifficulty to start the program. Many of my methods use hiddenWord so I pasted all of my code below incase you need to check that. Otherwise, the main parts that I feel like that are causing problems are in the area where I declare my field variables, my randomWord method, and the main method.
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
public class HangmanGame {
static String[] easyDifficulty = new String[]{"orange", "jacket","shirt"
,"rocket","airplane","circle","balloon","swing","truck","caterpillar"};
static Random rand = new Random();
static String hiddenWord = new String("");
static char[] hiddenWordToChar = hiddenWord.toCharArray();
static int triesLeft = 6;
static boolean done = false;
static int length = hiddenWord.length();
static Scanner input = new Scanner(System.in);
final static int maxLength = 30;
static char[] repeatChecker = new char[30]; //this is to help prevent the user from putting the same char multiple times
static char[] fillWord = new char[length];
static int var;
static int var2;
static char underscore = '_';
static int chooseDifficultyInt;
public static String randomWord(int n) {
int randomNum = rand.nextInt(9);
int difficultyInt = n;
if (difficultyInt == 1){
//System.out.println(easyDifficulty[randomNum]);
return easyDifficulty[randomNum];
}
return null;
}
public static boolean contains(char[] arr, char i) {
for (char n : arr) {
if (i == n) {
return true;
}
}
return false;
}
public static boolean multiLetter(char[] arr, char i){
int multiple = 0;
for (char n : arr){
if (i == n){
multiple++;
//continue;
}
}
System.out.println(multiple);
if (multiple > 1){
return true;
}
else {
return false;
}
}
public static void createSpaces(int n){
for (int i = 0; i <= n-1; i++){
fillWord[i] = underscore;
}
System.out.println(fillWord);
}
public static void tryAgain(){
System.out.println("Would you like to try again? Enter Y/N to go again or quit!");
char goAgain = input.next().charAt(0);
goAgain = Character.toLowerCase(goAgain);
if (goAgain == 'y') {
triesLeft = 6;
repeatChecker = new char[20];
main(null);
}
else if (goAgain == 'n') {
System.out.println("Bye!");
System.exit(0);
}
else {
System.out.println("Invalid input");
tryAgain();
}
}
public static void arrayLetters(){
System.out.println("This is a " + length + " letter word. Please enter a letter to guess: ");
char charInput = input.next().charAt(0);
char[] letters = new char[20];
//This code only runs if the user inputs a letter that repeats
//throughout hiddenWord
if (multiLetter(hiddenWordToChar, charInput)){
for (int n = 0; n < length; n++){
char multiWordLetter = hiddenWord.charAt(n);
letters[n] = multiWordLetter;
if (letters[n] == charInput){
fillWord[n] = charInput;
}
if (contains(repeatChecker, charInput)){
System.out.println("You already did that word, try again!");
arrayLetters();
}
if (Arrays.equals(fillWord, hiddenWordToChar)){
System.out.println("Congratulations, you win! The word was '" + hiddenWord + "'!");
System.out.println("You completed the challenge in " + triesLeft + " tries! \n\n");
tryAgain();
}
}
System.out.println(fillWord);
System.out.println("Nice! There is a(n) " + charInput + " in this word!");
System.out.println("You have " + triesLeft + " tries left!\n");
arrayLetters();
}
//This block of code runs when the user input a letter that only occurs once
//in hiddenWord
for (int i = 0; i < length; i++){
char wordLetter = hiddenWord.charAt(i);
letters[i] = wordLetter;
if (contains(letters, charInput)){
/*
if (multiLetter(letters, charInput)){
System.out.println("aylmao");
}
*/
//System.out.println(multiLetter(hiddenWordArray, charInput));
if (contains(repeatChecker, charInput)){
System.out.println("You already did that word, try again!");
arrayLetters();
}
repeatChecker[var] = charInput;
var++;
fillWord[i] = charInput;
if (Arrays.equals(fillWord, hiddenWordToChar)){
System.out.println("Congratulations, you win! The word was '" + hiddenWord + "'!");
System.out.println("You completed the challenge in " + triesLeft + " tries! \n\n");
tryAgain();
}
System.out.println(fillWord);
System.out.println("Nice! There is a(n) " + charInput + " in this word!");
System.out.println("You have " + triesLeft + " tries left!\n");
arrayLetters();
}
if (i == length-1){
System.out.println("There is no " + charInput + " in this word!");
triesLeft--;
System.out.println("You have " + triesLeft + " tries left!\n");
if (triesLeft <= 0){
System.out.println("You failed!\n\n");
tryAgain();
}
arrayLetters();
}
}
}
public static void main(String[] args) {
System.out.println("Welcome to my hangman game!");
System.out.println("Please input your prefered difficulty level.");
System.out.println("1. Easy");
System.out.println("2. Medium");
System.out.println("3. Hard");
chooseDifficultyInt = input.nextInt();
randomWord(chooseDifficultyInt);
hiddenWord = randomWord(chooseDifficultyInt);
createSpaces(length);
arrayLetters();
}
}
I'm an intermediate in java programming so I've learned that Strings are immutable. Thus I've considered that the reason why hiddenWord won't be set equal to randomWord(chooseDifficultyInt); is because of that?
I'm an intermediate in java programming so I've learned that Strings are immutable
This often causes confusion among new programmers. This is correct, Strings are immutable. However the variable that points to that String can be re-assigned (assuming it isn't final).
You can modify your hidden word as many times as you like:
HangmanGame.hiddenWord = "MyNewWord";
HangmanGame.hiddenWord = "AnotherWord";
HangmanGame.hiddenWord = "ThisWorks";
You might be wondering how the hiddenWord is changing if Strings are immutable.
Your variable isn't actually changing. Every time you re-assign it, a new String is being created. This means that the Strings themselves are never modified.
So yes, you can call
HangmanGame.hiddenWord = HangmanGame.randomWord(n);
and it will work perfectly.
Your initialization of hiddenWord as new String(""); is useless. You could remove it safely.
When you do that:
hiddenWord = randomWord(chooseDifficultyInt);
you set hiddenWord to the reference of a random string of your predefined list, not allocating anything, just reusing an existing string reference.

I'm having a few errors - Java program [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
This is really odd, I wrote a class for this program and was about to test how it reads data in from the file but I'm getting a "Cannot find symbol" error that refers to the "new" in the first scanner declared. The same error for the "=" in the second Scanner variable, and a bunch of cannot find symbols for all the "Candidate_Info[i]" objects later on. I dunno where my error is. I'm using notepad++ by the way, compiling and running it using notepad++ too.
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File CFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(Cfile);
File CfileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(CFileReadIn);
String StateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int NumberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
StateName = scanReadIn.next(); //The prime read for the while loop
int NumberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(StateName != "END_OF_FILE") //While we haven't reached the end of the file
{
for(int i = scanReadIn.nextInt(); i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
NumberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
StateName = scanReadIn.next(); //Pull the next state name
}
Candidate_Info Candidates [] = new Candidate_Info [NumberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < NumberOfCandidates; i++) //Running the constructor for each and every candidate created
{
Candidate_Info [i] = Candidate_Info();
}
StateName = scan.next(); //Prime read for the data taking loop
while(StateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int CandidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
for(int i = 0; i < scan.nextInt(); i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
Candidate_Info[CandidateNumber].setState(StateName);
Candidate_Info[CandidateNumber].setName(scan.next());
Candidate_Info[CandidateNumber].setOffice(scan.next());
Candidate_Info[CandidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
Candidate_Info[CandidateNumber].setVotes(scan.nextInt());
Candidate_Info[CandidateNumber].setSpent(scan.nextDouble());
Candidate_Info[CandidateNumber].setMotto(scan.nextLine());
CandidateNumber++;
}
StateName = scan.next();
}
}
}
And here's the code for the Class I wrote.
//Samuel James Huntowski
// started: 11-18-2014
// last modified: 11-18-2014
public class Candidate_Info
{
private String State; //All the variables that were given to me in the specification
private String Name_of_Candidate;
private String Election_Office;
private char Party;
private int Number_of_Votes;
private double Dollars_Spent;
private String Motto;
private final double DOLLARS_SPENT_MIN = 0.0; //Mutator method for Dollars_Spent must check to see if greater then this value
private final int NUMBER_OF_ATTRIBUTES = 7; //for use in the equals method
public Candidate_Info()
{
State = "No state assigned"; //Giving empty values to all of the variables
Name_of_Candidate = "No name yet";
Election_Office = "No office assigned";
Party = 'X';
Number_of_Votes = 0;
Dollars_Spent = 0.0;
Motto = "No motto yet";
}
//These are all of the Accessor Methods
public String getState()
{
return State;
}
public String getName()
{
return Name_of_Candidate;
}
public String getOffice()
{
return Election_Office;
}
public char getParty()
{
return Party;
}
public int getVotes()
{
return Number_of_Votes;
}
public double getSpent()
{
return Dollars_Spent;
}
public String getMotto()
{
return Motto;
}
//Mutator methods will go here
public void setState(String newState)
{
State = newState;
System.out.println("The candidate's state is now set to " + newState + ".");
}
public void setName(String newName)
{
Name_of_Candidate = newName;
System.out.println("The candidate's name is now set to " + newName + ".");
}
public void setOffice(String newOffice)
{
Election_Office = newOffice;
System.out.println("The candidate's office is now set to " + newOffice + ".");
}
public void setParty(char newParty)
{
if(!((newParty == 'd') || (newParty == 'r') || (newParty == 'i') || (newParty == 'o'))) //If the value of newParty DOES NOT EQUAL 'o', 'd', 'r', or 'i' then do the next set of code
{
System.out.println("Invalid party input. Candidate's party remains unchanged. Please try again.");
}
else
{
Party = newParty;
System.out.println("The candidate's party is now set to " + newParty + ".");
}
}
public void setVotes(int newNumberOfVotes)
{
Number_of_Votes = newNumberOfVotes;
System.out.println("The candidate's number of votes is now set to " + newNumberOfVotes + ".");
}
public void setSpent(double newDollarsSpent)
{
if(newDollarsSpent < DOLLARS_SPENT_MIN) //If the amount of money spent is less then zero (Which just wouldn't make sense, so that's why I set the variable to zero)
{
System.out.println("New amount of dollars spent is invalid. Candidate's dollars spent remains unchanged. Please try again.");
}
else
{
Dollars_Spent = newDollarsSpent;
System.out.println("The candidate's dollars spent is now set to " + newDollarsSpent + ".");
}
}
public void setMotto(String newMotto)
{
Motto = newMotto;
System.out.println("The candidate's motto is now set to \"" + newMotto + "\"");
}
public void displayAll()
{
System.out.println(State + "\t" + Name_of_Candidate + "\t"
+ Election_Office + "\t" +
Party + "\t" + Number_of_Votes +
"\t" + Dollars_Spent + "\t" + Motto); //Display all info separated by tabs
}
public String toString()
{
String ReturnThis = (State + "\t" + Name_of_Candidate + "\t" +
Election_Office + "\t" + Party +
"\t" + Number_of_Votes + "\t" +
Dollars_Spent + "\t" + Motto); //same as displayAll() just in one string
return ReturnThis;
}
public boolean equals(Candidate_Info PassedCandidate)
{
boolean TF [] = new boolean [NUMBER_OF_ATTRIBUTES]; //An array of booleans that match the number of attributes above
boolean finalResult; //This will hold the final boolean result of all the below calculations
if(State.equals(PassedCandidate.getState())) TF[0] = true; //This isn't the most graceful method of doing this, but it works
else TF[0] = false;
if(Name_of_Candidate.equals(PassedCandidate.getName())) TF[1] = true;
else TF[1] = false;
if(Election_Office.equals(PassedCandidate.getOffice())) TF[2] = true;
else TF[2] = false;
if(Party == PassedCandidate.getParty()) TF[3] = true;
else TF[3] = false;
if(Number_of_Votes == PassedCandidate.getVotes()) TF[4] = true;
else TF[4] = false;
if(Dollars_Spent == PassedCandidate.getSpent()) TF[5] = true;
else TF[5] = false;
if(Motto.equals(PassedCandidate.getMotto())) TF[6] = true;
else TF[6] = false;
if(TF[0] && TF[1] && TF[2] && TF[3] && TF[4] && TF[5] && TF[6]) finalResult = true; //If ALL OF THE ATTRIBUTES equal the attributes of the passed candidate, therefore making all the TF variables true, then they are equal
else finalResult = false;
return finalResult;
}
}
Samuel, try and use the "camelCase" naming convention where the first letter of a variable name is lowercase, not uppercase. Only classes should get uppercase first letters. That lets you easily identify whether something is a class or a variable.
Not doing this has already resulted in a small mistake in the beginning of your code, where you accidentally refer to the CFile variable as Cfile, which Java will interpret as two different things. This is why you were getting the error about not being able to find the symbol, because Java didn't know what Cfile was, only CFile.
I also took a look lower in your code. You create a candidates variable, but then accidentally keep referring to it by its class Candidate_Info in the for and while loops.
To construct a new object out of a class, you must put the new keyword before it. You cannot just directly reference the constructor method as you did in the for loop.
Here's a version that may better show what I mean:
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File cFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(cFile);
File cFileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(cFileReadIn);
String stateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int numberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
stateName = scanReadIn.next(); //The prime read for the while loop
int numberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(stateName != "END_OF_FILE") //While we haven't reached the end of the file
{
for(int i = scanReadIn.nextInt(); i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
numberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
stateName = scanReadIn.next(); //Pull the next state name
}
Candidate_Info candidates [] = new Candidate_Info [numberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < numberOfCandidates; i++) //Running the constructor for each and every candidate created
{
candidates[i] = new Candidate_Info();
}
stateName = scan.next(); //Prime read for the data taking loop
while(stateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int candidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
for(int i = 0; i < scan.nextInt(); i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
candidates[candidateNumber].setState(stateName);
candidates[candidateNumber].setName(scan.next());
candidates[candidateNumber].setOffice(scan.next());
candidates[candidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
candidates[candidateNumber].setVotes(scan.nextInt());
candidates[candidateNumber].setSpent(scan.nextDouble());
candidates[candidateNumber].setMotto(scan.nextLine());
candidateNumber++;
}
stateName = scan.next();
}
}
}
Note that without your text files, it's going to be hard to determine how your code will actually work, but I just wanted to warn you about a common problem with Scanner when you mix nextInt with nextLine. See this.

Error with next int versus next line

The other question I asked was excellently answered, but at the end the person mentioned an issue with taking an int and not clearing to the next line in the file. I tried a few different things (the commented out stuff in my code that you will see) and nothing seems to work. I always get the same error no matter what I changed. Here is the error, my code, my class code, then the file in that order.
The error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at HuntowskiSamuel.main(HuntowskiSamuel.java:25)
The code section:
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File cFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(cFile);
File cFileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(cFileReadIn);
String StateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int NumberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
StateName = scanReadIn.next(); //The prime read for the while loop
//garbage = scan.nextLine(); //Consuming the newline character
int NumberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(StateName != "END_OF_FILE") //While we haven't reached the end of the file
{
int i = scanReadIn.nextInt();
garbage = scan.nextLine(); //Getting rid of the whitespace after the int is taken
for(i=i; i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
NumberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
StateName = scanReadIn.next(); //Pull the next state name
//garbage = scan.nextLine(); //Consuming the newline after the state pull
}
Candidate_Info candidates [] = new Candidate_Info [NumberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < NumberOfCandidates; i++) //Running the constructor for each and every candidate created
{
candidates[i] = new Candidate_Info();
}
StateName = scan.next(); //Prime read for the data taking loop
//garbage = scan.nextLine(); //Getting rid of the whitespace after the state
while(StateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int CandidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
int candidatesPerState = scan.nextInt();
garbage = scan.nextLine(); //To get rid of the rest of the whitespace after the int return
for(int i = 0; i < candidatesPerState; i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
candidates[CandidateNumber].setState(StateName);
candidates[CandidateNumber].setName(scan.next());
candidates[CandidateNumber].setOffice(scan.next());
candidates[CandidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
candidates[CandidateNumber].setVotes(scan.nextInt());
candidates[CandidateNumber].setSpent(scan.nextDouble());
candidates[CandidateNumber].setMotto(scan.nextLine());
CandidateNumber++;
}
StateName = scan.next();
//garbage = scan.nextLine(); //To get rid the whitespace after taking the state value
}
}
}
The class code:
//Samuel James Huntowski
// started: 11-18-2014
// last modified: 11-18-2014
public class Candidate_Info
{
private String State; //All the variables that were given to me in the specification
private String Name_of_Candidate;
private String Election_Office;
private char Party;
private int Number_of_Votes;
private double Dollars_Spent;
private String Motto;
private final double DOLLARS_SPENT_MIN = 0.0; //Mutator method for Dollars_Spent must check to see if greater then this value
private final int NUMBER_OF_ATTRIBUTES = 7; //for use in the equals method
public Candidate_Info()
{
State = "No state assigned"; //Giving empty values to all of the variables
Name_of_Candidate = "No name yet";
Election_Office = "No office assigned";
Party = 'X';
Number_of_Votes = 0;
Dollars_Spent = 0.0;
Motto = "No motto yet";
}
//These are all of the Accessor Methods
public String getState()
{
return State;
}
public String getName()
{
return Name_of_Candidate;
}
public String getOffice()
{
return Election_Office;
}
public char getParty()
{
return Party;
}
public int getVotes()
{
return Number_of_Votes;
}
public double getSpent()
{
return Dollars_Spent;
}
public String getMotto()
{
return Motto;
}
//Mutator methods will go here
public void setState(String newState)
{
State = newState;
System.out.println("The candidate's state is now set to " + newState + ".");
}
public void setName(String newName)
{
Name_of_Candidate = newName;
System.out.println("The candidate's name is now set to " + newName + ".");
}
public void setOffice(String newOffice)
{
Election_Office = newOffice;
System.out.println("The candidate's office is now set to " + newOffice + ".");
}
public void setParty(char newParty)
{
if(!((newParty == 'd') || (newParty == 'r') || (newParty == 'i') || (newParty == 'o'))) //If the value of newParty DOES NOT EQUAL 'o', 'd', 'r', or 'i' then do the next set of code
{
System.out.println("Invalid party input. Candidate's party remains unchanged. Please try again.");
}
else
{
Party = newParty;
System.out.println("The candidate's party is now set to " + newParty + ".");
}
}
public void setVotes(int newNumberOfVotes)
{
Number_of_Votes = newNumberOfVotes;
System.out.println("The candidate's number of votes is now set to " + newNumberOfVotes + ".");
}
public void setSpent(double newDollarsSpent)
{
if(newDollarsSpent < DOLLARS_SPENT_MIN) //If the amount of money spent is less then zero (Which just wouldn't make sense, so that's why I set the variable to zero)
{
System.out.println("New amount of dollars spent is invalid. Candidate's dollars spent remains unchanged. Please try again.");
}
else
{
Dollars_Spent = newDollarsSpent;
System.out.println("The candidate's dollars spent is now set to " + newDollarsSpent + ".");
}
}
public void setMotto(String newMotto)
{
Motto = newMotto;
System.out.println("The candidate's motto is now set to \"" + newMotto + "\"");
}
public void displayAll()
{
System.out.println(State + "\t" + Name_of_Candidate + "\t"
+ Election_Office + "\t" +
Party + "\t" + Number_of_Votes +
"\t" + Dollars_Spent + "\t" + Motto); //Display all info separated by tabs
}
public String toString()
{
String ReturnThis = (State + "\t" + Name_of_Candidate + "\t" +
Election_Office + "\t" + Party +
"\t" + Number_of_Votes + "\t" +
Dollars_Spent + "\t" + Motto); //same as displayAll() just in one string
return ReturnThis;
}
public boolean equals(Candidate_Info PassedCandidate)
{
boolean TF [] = new boolean [NUMBER_OF_ATTRIBUTES]; //An array of booleans that match the number of attributes above
boolean finalResult; //This will hold the final boolean result of all the below calculations
if(State.equals(PassedCandidate.getState())) TF[0] = true; //This isn't the most graceful method of doing this, but it works
else TF[0] = false;
if(Name_of_Candidate.equals(PassedCandidate.getName())) TF[1] = true;
else TF[1] = false;
if(Election_Office.equals(PassedCandidate.getOffice())) TF[2] = true;
else TF[2] = false;
if(Party == PassedCandidate.getParty()) TF[3] = true;
else TF[3] = false;
if(Number_of_Votes == PassedCandidate.getVotes()) TF[4] = true;
else TF[4] = false;
if(Dollars_Spent == PassedCandidate.getSpent()) TF[5] = true;
else TF[5] = false;
if(Motto.equals(PassedCandidate.getMotto())) TF[6] = true;
else TF[6] = false;
if(TF[0] && TF[1] && TF[2] && TF[3] && TF[4] && TF[5] && TF[6]) finalResult = true; //If ALL OF THE ATTRIBUTES equal the attributes of the passed candidate, therefore making all the TF variables true, then they are equal
else finalResult = false;
return finalResult;
}
}
And the file:
Illinois
3
Obama President d 131313 19.21 Great in 2008!
Daley Mayor d 5678 89000.45 My dad was good!
Stevenson Governor d 2367 43877.45 My hair is bad!
Wisconsin
6
Smith Mayor r 3 5.98 You can count on me daily!
Bush President r 11004 1222888.44 My dad was good too!
Gore President d 11003 54.34 Hear my Gore-y details!
Kim Governor r 111 3212.16 I'm the other Guy!
Hanrath Instructor i 6 0.12 What, me worry?
Jones Instructor o 9 14.56 You'd better worry!
Alaska
4
Nader President o 2 50.00 Nader's Raiders!
Alexander Mayor i 13 13.13 What am I doing?
Thompson Governor o 1 0.00 And you thought I was gone!
Schwarzenegger President o 123 1233377.94 I'll be back!
Delaware
2
Allen Instructor i 147 16.71 No exams in cs105!
Stewart President o 3 27367.67 I'm a good thing!
END_OF_FILE
Each of the data values of the file is seperated by a tab, but I didn't think that would matter as the methods that I use stop at the whitespace. Was I wrong? Where did I screw up? This is all happening at run time by the way. It compiles fine after you guys helped me earlier.

BabyNames how to return only one line

I have an assignment where the user is asked for baby name using a scanner. Then it reads through files names.txt and meanings.txt and returns the popularity of the name for each decade ranging from 1890 - 2010 then it prints out the meaning. Some names have multiple meanings and some are used in both genders. The assignment states to print only the first line where the name is found. I am having trouble only returning the first line in which the name is found. PLEASE HELP ME!
import java.io.*;
import java.util.*;
public class BabyNames4 {
public static void main(String[] args) throws FileNotFoundException {
printIntro();
Scanner console = new Scanner(System.in);
System.out.print("Name: ");
String searchWord = console.next();
Scanner fileScan = new Scanner(new File("names.txt"));
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan);
}
}
Scanner fileScan2 = new Scanner(new File("meanings.txt"));
String dataLine2 = find(searchWord, fileScan2);
if (dataLine2.length() > 0) {
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
}
}
public static void printIntro() {
System.out.println("This program allows you to search through the");
System.out.println("dada from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since 1890");
System.out.println();
}
public static String find(String searchWord, Scanner fileScan) {
while (fileScan.hasNextLine()) {
String dataLine = fileScan.nextLine();
String dataLineLC = dataLine.toLowerCase();
if (dataLineLC.contains(searchWord.toLowerCase())) {
return dataLine;
//} else { runs a continuous loop
//System.out.println(search" not found.");
}
}
return "";
}
public static void printName(String dataLine) {
Scanner lineScan = new Scanner(dataLine);
String name = lineScan.next();
String gender = lineScan.next();
String rank = "";
while (lineScan.hasNext()) {
rank += lineScan.next() + " ";
}
System.out.println(name + (" ") + gender + (" ") + rank);
}
public static void printMeaning(String dataLine2) {
Scanner lineScan2 = new Scanner(dataLine2);
String name2 = lineScan2.next();
String gender2 = lineScan2.next();
String language = lineScan2.next();
String meaning = "";
while (lineScan2.hasNext()) {
meaning += lineScan2.next() + " ";
}
System.out.println(name2 + (" ") + gender2 + (" ") + language + (" ") + meaning);
}
}
It looks like sushain hit it with his comment.
The loop:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
could be changed to:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
break;
}
This way you do not find the second definition and do not print it.
In this loop, you don't need to find the next line, correct?
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan); // remove this line
}
}
If you remove the next find to dataLine and remove the while blocks in both instances where you search the file, you won't need a break, and you'll only end up printing one instance.
Do this:
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
printName(dataLine);
}

Categories

Resources