Trouble matching states to capitals - java

I created two arrays and assigned states to one array and capitals to the other array that I got from a text file. The text file is formatted like this:
Colorado,Denver,
Wisconsin,Madison,
..........etc
My code is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StatesAndCapitals {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream is = new FileInputStream("capitals.txt");
Scanner input = new Scanner(is);
String[] states = new String[50];
String[] capitals = new String[50];
for (int i = 0; i < states.length; i++){
String currentLine = input.nextLine();
int a = currentLine.indexOf(",");
String states1 = currentLine.substring(0, a);
states[i] = states1;
int b = currentLine.lastIndexOf(",");
String capitals1 = currentLine.substring(a+1, b);
capitals[i] = capitals1;
}//end for loop
}
}
The point of my program is to ask "What is the capital of (blank)?"
Then I need to tell the person if they are correct or not. The problem I'm having is that I don't know how to check if, for example, Madison is the capital of Wisconsin. Any help would be appreciated.

public static void main(String[] args) {
Scanner userInput = null;
Scanner scanner = null;
try {
userInput = new Scanner(System.in);
scanner = new Scanner(new File("capitals.txt"));
while (scanner.hasNext()) {
String[] stateAndCapital = scanner.next().split(",");
System.out.println(String.format("What is the capital of %s?",
stateAndCapital[0]));
System.out.println(userInput.next().equals(stateAndCapital[1]));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
userInput.close();
}
}
output:
What is the capital of Colorado?
dunno
false
What is the capital of Wisconsin?
Madison
true

Try using this:
public boolean isCapitalOfState(String capital, String state) {
for (int i = 0; i < state.length; i++) {
if (state[i].equals(state) && capitals[i].equals(capital)) {
return true;
}
}
return false;
}
It loops through the array of states and once it has found the match, it will check if the capital matches, if so return true. If it has not found anything it will by default return false.
Note though that there are a lot of easier ways to achieve your behaviour. Generally, Lists are superior to Arrays.
EDIT: I see your question asks for a bit more, we here cannot give you a full program to do it. However do keep in mind that when you've already obtained an index in state, that you can check the result way easier than this.

These are setup like parallel arrays correct? Meaning for example states[0] = colorado, and capitals[0] = denver, it looks this way but if it is indeed setup like this use the index of the state as the index for the capital and compare the input against that.
For example,
System.out.println("What is the capital of " + states[i]);
capital = input.nextLine();
if(capital.equals(capitals[i]){
return true;
}
else{
return false;
}

Related

Why is my radix sorting algorithm returning a partially sorted list?

First off I want to point out that this assignment is homework /but/ I am not looking for a direct answer, but rather at a hint or some insight as to why my implementation is not working.
Here is the given: We are provided with a list of words of 7 characters long each and are asked to sort them using the Radix Sorting Algorithm while using queues.
EDIT 1: Updated Code
Here is my code:
import java.util.*;
import java.io.File;
public class RadixSort {
public void radixSort() {
ArrayList<LinkedQueue> arrayOfBins = new ArrayList<LinkedQueue>();
LinkedQueue<String> masterQueue = new LinkedQueue<String>();
LinkedQueue<String> studentQueue = new LinkedQueue<String>();
//Creating the bins
for (int i = 0; i < 26; i++) {
arrayOfBins.add(new LinkedQueue<String>());
}
// Getting the file name and reading the lines from it
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with its extension: ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
masterQueue.enqueue(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
for (int p = 6; p >= 0; p--) {
for (LinkedQueue queue : arrayOfBins) {
queue.clear();
}
while (masterQueue.isEmpty() == false) {
String s = (String) masterQueue.dequeue();
char c = s.charAt(p);
arrayOfBins.get(c-'a').enqueue(s);
}
for (LinkedQueue queue : arrayOfBins) {
studentQueue.append(queue);
}
}
masterQueue = studentQueue;
System.out.println(masterQueue.size());
System.out.println(masterQueue.dequeue());
}
public static void main(String [] args) {
RadixSort sort = new RadixSort();
sort.radixSort();
}
}
I can see so many problems, I'm not sure how you get an answer at all.
Why do you have two nested outermost loops from 0 to 6?
Why don't you ever clear studentQueue?
The j loop doesn't execute as many times as you think it does.
Aside from definite bugs, the program doesn't output anything -- are you just looking at the result in the debugger? Also are you actually allowed to assume that the words will contain no characters besides lowercase letters?

Java Beginning Scanner

I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide. I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want. After searching for any help I haven't been able to find my issue that I am having. So far I have this:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
For any input that I input there is no result. I don't get an Error Message or any form of return... The output is blank. I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created. I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up. Thank you for your time and help.
You need to print the output, for example
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...
You can use String#charAt to get an individual character from a String at a given index
Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1
null + String = nullString ;)
You can run a loop backwards. for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)

Parse different types of data from input java

Different lists of data will be entered on command line.
"J,A,V,A"
"4,H,11,V,3,H"
I need to store the first list in a char array. I also want to have the next line in a char array of "H,V,H" and an int array of "4,11,3". What is the best way to go about doing this? I'm hesitant to split on the comma because I don't know if the input is going to be separated by just a comma or a comma and a space. I'm having difficulty since when I use a scanner everything stays in a string, and when I try to split it the string becomes a string array.
I'm having difficulty since when I use a scanner everything stays in a string, and when I try to split it the string becomes a string array.
The following seems to work for me.. Only ran it in the debugger, but it workd on the two lines of input you provided.
import java.lang.System;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Character> chars = new ArrayList<Character>();
Scanner console = new Scanner(System.in);
while (console.hasNext()) {
String line = console.next();
String[] tokens = line.split("\\s*,\\s*");
for (int i = 0; i < tokens.length; i++) {
if (isInteger(tokens[i])) {
ints.add(Integer.parseInt(tokens[i]));
} else if (isChar(tokens[i])) {
chars.add((char) tokens[i].indexOf(0));
}
}
}
console.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
private static boolean isChar(String s) {
if (s.length() != 1) {
return false;
}
return true;
}
}

Using a method to call individual strings from an array (looping)

This is the question from my assignment that I am unsure of:
The class is to contain a public method nextWord(). When a new line is read, use the String method .split("\s+") to create an array of the words that are on the line. Each call to the nextWord() method is to return the next word in the array. When all of the words in the array have been processed, read the next line in the file. The nextWord()method returns the value null when the end of the file is reached.
I have read the file, and stored each individual string in an array called tokenz.
I'm not sure how I can have a method called "nextWord" which returns each individual word from tokenz one at a time. Maybe I don't understand the question?
The last part of the question is:
In your main class, write a method named processWords() which instantiates the MyReader class (using the String "A2Q2in.txt"). Then write a loop that obtains one word at a time from the MyReader class using the nextWord() method and prints each word on a new line.
I've thought of ways to do this but I'm not sure how to return each word from the nextWord method i'm supposed to write. I can't increase a count because after the String is returned, anything after the return statement cannot be reached because the method is done processing.
Any help would be appreciated, maybe I'm going about this the wrong way?
Can't use array lists or anything like that.
Here is my code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class A2Q2
{
public static void main (String [] args)
{
processWords();
}
public static void processWords()
{
MyReader reader = new MyReader("A2Q2.txt");
String[] words = new String[174];
words[0] = reader.nextWord();
System.out.println(words[0]);
}
}
class MyReader
{
static String name;
static BufferedReader fileIn;
static String inputLine;
static int tokensLength = 0;
static String[] tokens;
static int counter = 0;
// constructor.
public MyReader(String name)
{
this.name = name;
}
public static String[] readFile()
{
String[] tokenz = new String[174];
int tokensLength = 0;
try
{
fileIn = new BufferedReader (new FileReader(name));
inputLine = fileIn.readLine();
while(inputLine !=null)
{
tokens = inputLine.split("\\s+");
for (int i = 0 ; i < tokens.length; i++)
{
int j = i + tokensLength;
tokenz[j] = tokens[i];
}
tokensLength = tokensLength + tokens.length;
inputLine = fileIn.readLine();
}
fileIn.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
}
//FULL ARRAY OF STRINGS IN TOKENZ
return tokenz;
}
public static String nextWord()
{
String[] tokenzz = readFile();
//????
return tokenzz[0];
}
}
Here's a conceptual model for you.
Keep track of your MyReader's state to know which value to return next.
the following example uses tokenIndex to decide where to read at next.
class MyReader
{
String[] tokens;
int tokenIndex = 0;
public String nextWord()
{
if(tokens == null || tokens.length <= tokenIndex)
{
// feel free to replace this line with whatever logic you want to
// use to fill in a new line.
tokens = readNextLine();
tokenIndex = 0;
}
String retVal = tokens[tokenIndex];
tokenIndex++;
return retval;
}
}
Mind you, this isn't a complete solution(it doesn't check for the end of file for instance), only a demonstration of the concept. You might have to elaborate a bit.
Use a loop and process each element in the array, printing them one at a time?

Java logical OR as per user input

Requirement:
The program looks if a string is equal to the one or any of the characters entered by the user. The user may enter any numbers of entries separated by commas.
In essence the code should be
if user inputs one value (X) // in[0] = X;
if(str.equals(in[0]))
{
// do something
}
if user inputs two values (X,Y) // in[0] = X; in[1] = Y;
if(str.equals(in[0]) || str.equals(in[1]))
{
// do something
}
if user inputs three values (X,Y,Z) // in[0] = X; in[1] = Y; in[2] = Z;
if(str.equals(in[0]) || str.equals(in[1]) || str.equals(in[2]))
{
// do something
}
And so on......
As you can see I cannot write such a dynamic if statement.
I would have liked to have something like the below work. Any suggestions?
Trial code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class test {
public static void main (String[] args) throws Exception {
System.out.println("Enter the characters separated by commas");
BufferedReader consoleinput = new BufferedReader(new InputStreamReader(System.in));
String input = consoleinput.readLine();
input = input.toUpperCase();
String[] in = input.split(",");
String str = "N";
if (str.equals(in))
{
System.out.println("Match found");
}
else
{
System.out.println("No match");
}
}
}
What you want is some sort of loop.
foreach(string str : in) {
//code here
}
The Apache Commons CLI library provides an API for parsing command line options passed to programs
Do you look for something like this?
if (Arrays.asList(in).contains(str)) {
// do something
}

Categories