Here I have created a flames game logic it is final string length is correct(eg:4 for two strings 'raja' and 'rani') based on length I need to show 'f' or 'l' or 'a' or 'm' or 'e' or 's'.
I have written logic based on length that character is visible but that is not my concern. For length 4 result should be 'e'(in flames for length 4 first 'm' should remove then 'l' then 'f' then 'a' then 's' finally i need 'e' as output.Can anybody tell me idea. This is my code.
public static void main(String[] args) {
String name1 = "raja";
String name2 = "rani";
String s1 = name1;
String s2 = name2;
for (int i = 0; i < name1.length(); i++) {
for (int j = 0; j < name2.length(); j++) {
if (name1.charAt(i) == name2.charAt(j)) {
name1 = name1.replaceFirst(String.valueOf(name1.charAt(i)), "#");
name2 = name2.replaceFirst(String.valueOf(name2.charAt(j)), "#");
}
}
}
String result = name1 + name2;
result = result.replaceAll("#", "");
int resultLength = result.length();
String baseInput = "flames";
char relationIs = 0;
int temp = 0;
if (resultLength > 0) {
temp = resultLength % baseInput.length();
}
if (temp == 0 && resultLength >= 6) {
relationIs = 's';
} else {
int count = temp - 1;
if (count >= 0) {
relationIs = baseInput.charAt(count);
System.out.println("Relation Betw " + s1 + " and " + s2 + " is:");
}
}
switch (relationIs) {
case 'f':
System.out.println("friendship");
break;
case 'l':
System.out.println("Lovers");
break;
case 'a':
System.out.println("Affection");
break;
case 'm':
System.out.println("Marriage");
break;
case 'e':
System.out.println("Enemity");
break;
case 's':
System.out.println("Siblings");
break;
default:
System.out.println("FLAME Test works only for different names");
break;
}
}
Logic follows this order:only forward direction remove 4 character.
if length=4
step 0:flames ('f' as 1)
step 1:flaes (here 'e' as 1)
step 2:faes (here 'a' as 1)
step 3:aes (here 'a' as 1)
step 4:es (here 'e' as 1)
step 5:e //output.
Your help will be appreciated.
Hope this is what you need. I am here striking the character of the word flames until i am getting one character. Once i get the character that is what the result of flames.
if (resultLength > 0) {
while (baseInput.length() !=1)
{
System.out.println(baseInput);
int tmpLen = resultLength % baseInput.length(); //finding char position to strike
if(tmpLen != 0)
{
temp = baseInput.substring(tmpLen) + baseInput.substring(0, tmpLen-1); //Append part start from next char to strike and first charater to char before strike.
}
else
{
temp = baseInput.substring(0, baseInput.length()-1); //If mod result zero we can strike last letter easily
}
baseInput = temp; //Assign the temp to baseinput for next iteration.
}
relationIs = baseInput.charAt(0);
System.out.println(relationIs);
}
Link : http://ideone.com/Fqgcc1
I think the problem is with this line:
int count = temp - 1;
Which is giving you an answer of 3 which gives (0)F (1)L (2)A (3)M
So change it to:
int count = temp; //- 1;
To get (0)F (1)L (2)A (3)M (4)E
// Another Right Code to Find FLAMES in JAVA
// It is simple
import java.util.Scanner;
class Flames
{
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
String name,fname,flm="flames";
System.out.println("Enter the boy name...");
name=sc.next();
System.out.println("Enter the girl name...");
fname=sc.next();
int l=name.length();
int gl=fname.length();
int num=0,tl=0;
char n[]=name.toCharArray();
char gn[]=fname.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<gl;j++)
{
if(n[i]==gn[j])
{
n[i]='*';
gn[j]='*';
break;
}
}
}
String tname=new String(n);
tname=tname+(new String(gn));
tname=tname.replace("*","");
tl=tname.length();
System.out.println(tl);
for(int s=6;s>=2;s--)
{
if(tl>s)
num=tl-s;
else
num=tl;
while(num>s)
{
num=num-s;
}
flm=flm.substring(num,flm.length())+(flm.substring(0,num-1));
}
switch(flm.charAt(0))
{
case 'f': System.out.println("Relationship = Friends"); break;
case 'l': System.out.println("Relationship = Lovers"); break;
case 'a': System.out.println("Relationship = Affections"); break;
case 'm': System.out.println("Relationship = Married"); break;
case 'e': System.out.println("Relationship = Enemy"); break;
case 's': System.out.println("Relationship = Brother & Sisters"); break;
}
//System.out.println("Name ="+flm);
}
}
import java.util.Scanner;
public class Flames {
public static void main(String[] args) {
/* Check the flames using two names */
Scanner scan = new Scanner(System.in);
System.out.print("Enter Name 1 : ");
String Name1 = scan.nextLine();
//System.out.println(Name1);
System.out.print("Enter Name 2 : ");
String Name2 = scan.nextLine();
//System.out.println(Name2);
int N1len = Name1.length();
int N2len = Name2.length();
Name1 = Name1.toLowerCase();
Name2 = Name2.toLowerCase();
StringBuffer NameB1 = new StringBuffer(Name1);
StringBuffer NameB2 = new StringBuffer(Name2);
int Name3=0;
for (int i = 0; i<N1len; i++)
{
for (int j = 0; j<N2len; j++)
{
if (NameB1.charAt(i) == NameB2.charAt(j))
{
NameB1 = NameB1.deleteCharAt(i);
NameB2 = NameB2.deleteCharAt(j);
N1len= NameB1.length();
N2len= NameB2.length();
i=0;
j=0;
}
}
}
Name3= NameB1.length()+NameB2.length();
//System.out.println(NameB1);
//System.out.println(NameB2);
//System.out.println(Name3);
/* Flames Calculation */
char flameResult =0;
String flames = "flames";
StringBuffer sb3 = new StringBuffer(flames);
while (sb3.length()!=1)
{
int Name4 = Name3%sb3.length();
String temp;
if(Name4!=0)
{
temp = sb3.substring(Name4)+sb3.substring(0, Name4-1);
}
else
{
temp=sb3.substring(0,sb3.length()-1);
}
sb3 = new StringBuffer(temp);
flameResult=sb3.charAt(0);
}
switch(flameResult)
{
case 'f': System.out.println("Friends");
break;
case 'l':
System.out.println("Love");
break;
case 'a':
System.out.println("Affection");
break;
case 'm':
System.out.println("Marriage");
break;
case 'e':
System.out.println("Enemies");
break;
case 's':
System.out.println("Sibling");
break;
}
}
}
import java.util.*;
public class Flames
{
public static void main()
{
int sp=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter two names");
String s=sc.nextLine().toLowerCase();
String s1=sc.nextLine().toLowerCase();
String p="flames";
String p1="flames";
String s2="";
String m="";
for(int i=0;i < s.length();i++)
{
if(Character.isLetter(s.charAt(i)))
{
m=m+s.charAt(i);
}
}
s=m;
m="";
for(int i=0;i < s1.length();i++)
{
if(Character.isLetter(s1.charAt(i)))
{
m=m+s1.charAt(i);
}
}
s1=m;
m="";
int l=s.length();
int l1=s1.length();
for(int i=0;i < l;i++)
{
int sl=0;
for(int j=0;j < s1.length();j++)
{
if(s.charAt(i)==s1.charAt(j))
{
if(sl==0)
{
sl++;sp++;s2=s2+" " ;
}
else
{
s2=s2+s1.charAt(j);
}
}
else
{
s2=s2+s1.charAt(j);
}
}
s1=s2;
s2="";
}
sp=sp*2;
int c=(l-1)+(l1-1)-(sp-1);
for(int i=1;;i++)
{
String z="";p=p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p;
String mn="";
char c1=p.charAt(c);
for(int j=0;j < p1.length();j++)
{
if(c1==p1.charAt(j))
{
mn=p1.substring(j+1)+mn;
break;
}
else
{
mn=mn+p1.charAt(j);
}
}
for(int k=0;k < p1.length();k++)
{
if(c1==p1.charAt(k))
{
}
else
{
z=z+p1.charAt(k);
}
}
p1=z;
p=mn;
if(mn.length()==1)
{
System.out.println(mn);
break;
}
}
}
}
Related
I'm trying to create a program that takes a file as an input and then counts the number of comments in that file. I've created a switch case to do so.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String file = new Scanner(new
File("file")).useDelimiter("\\Z").next();
int length, state, i, j;
state = 0;
i = 0;
j = 0;
while (i < file.length()) {
switch (state) {
case 0:
if (file.charAt(i) == '/') {
state = 1;
i++;
} else i++;
break;
case 1:
if (file.charAt(i) == '*') {
state = 2;
i++;
} else i++;
break;
case 2:
if (file.charAt(i) == '*') {
state = 3;
i++;
} else i++;
break;
case 3:
if (file.charAt(i) == '/') {
state = 4;
i++;
j++;
} else {
state = 2;
i++;
}
break;
case 4:
i++;
break;
default:
String nothing = "nothing";
}
}
System.out.println("Number of comments " + j);
}
The issue here is that it works up to 1 comment in the code. For example, if no comments exist the output would be:
#include <stdio.h>
int main()
{
int marks, i, num;
}
Number of comments: 0
If 1 exists:
#include <stdio.h>
int main()
{
/* comment */
int marks, i, num;
}
Number of comments: 1
If 2 exist:
#include <stdio.h>
int main()
{
/* comment */
/* comment 2 */
int marks, i, num;
}
Number of comments: 1
The issue being that it seems to be exiting my switch case as soon as it finds the first one. Is there a way to cycle this case back into the loop and start it all over again?
The issue with your approach is when the state is set to 4 ... which is when a comment block is detected. Instead, you should replace state = 4 with state = 0 in block of case 3.
After counting the first comment, your code is missing that state resetting logic in case 4.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String file = new Scanner(new
File("file")).useDelimiter("\\Z").next();
int length, state, i, j;
state = 0;
i = 0;
j = 0;
while (i < file.length()) {
switch (state) {
case 0:
if (file.charAt(i) == '/') {
state = 1;
i++;
} else i++;
break;
case 1:
if (file.charAt(i) == '*') {
state = 2;
i++;
} else i++;
break;
case 2:
if (file.charAt(i) == '*') {
state = 3;
i++;
} else i++;
break;
case 3:
if (file.charAt(i) == '/') {
state = 4;
i++;
j++;
} else {
state = 2;
i++;
}
break;
case 4:
i++;
state = 0;
break;
default:
String nothing = "nothing";
}
}
System.out.println("Number of comments " + j);
}
here in the findVowels function I am trying to print every 2nd vowel which I got from outPut function in rev but it just print the last vowel only....
import java.util.Scanner;
public class VowelString {
static char rev;
static String str;
static int count = 0;
void inPut() {
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
System.out.println(str);
sc.close();
}
void outPut() {
System.out.println(str);
// int length=str.length();
try {
for (int i = 0; i <= str.length() - 1; i++) {
if ((str.charAt(i) == 'a') || (str.charAt(i) == 'e')
|| (str.charAt(i) == 'i') || (str.charAt(i) == 'o')
|| (str.charAt(i) == 'u')) {
rev = str.charAt(i);
System.out.print(rev);
count++;
}
}
// System.out.println(rev);
System.out.println("\ntotal " + count);
} catch (IndexOutOfBoundsException e) {
System.out.println(e);
}
}
void findVowels(char word) {
this.rev = word;
String asta = String.valueOf(rev);
for (int i = 0; i <= asta.length() - 1; i = +2) {
char nawa = asta.charAt(i);
System.out.println("something = " + nawa);
}
}
public static void main(String[] args) {
VowelString vS = new VowelString();
vS.inPut();
// System.out.println("Values of Input " + vS);
vS.outPut();
// System.out.println("Values of OutPut " + vS);
vS.findVowels(rev);
}
}
You are only saving the last vowel you find to rev
rev = str.charAt(i);
inside output(). So rev in findVowel will only be 1 char it seems. Perhaps you mean to say
rev += str.charAt(i);
Though this is not recommendable in a general setting it will probably suffice for your problem unless you have huge Strings.
The posted code should print all vowels. Not only the last as you say. But also not every 2nd as you want. It's also poorly written. Here's one way to print every second vowel, and a bit better written overall:
for (int i = 0, count = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
if (count % 2 == 0) {
System.out.print(c);
}
break;
}
}
import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.
In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...
You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();
I'm doing an assignment where the goal is to, among other things, to add two large integers. Here is my code, spread out into four files.
Main that we cannot change:
import java.util.*;
import MyUtils.MyUtil;
public class CSCD210HW7
{
public static void main(String [] args)throws Exception
{
int choice;
String num;
LargeInt one, two, three = null;
Scanner kb = new Scanner(System.in);
num = HW7Methods.readNum(kb);
one = new LargeInt(num);
num = HW7Methods.readNum(kb);
two = new LargeInt(num);
do
{
choice = MyUtil.menu(kb);
switch(choice)
{
case 1: System.out.println(one + "\n");
break;
case 2: System.out.println("The value of the LargeInt is: " + two.getValue() + "\n");
break;
case 3: num = HW7Methods.readNum(kb);
one.setValue(num);
break;
case 4: if(one.equals(two))
System.out.println("The LargeInts are equal");
else
System.out.println("The LargeInts are NOT equal");
break;
case 5: three = two.add(one);
System.out.printf("The results of %s added to %s is %s\n", one.getValue(), two.getValue(), three.getValue());
break;
case 6: HW7Methods.displayAscendingOrder(one, two, three);
break;
default: if(two.compareTo(one) < 0)
System.out.printf("LargeInt %s is less than LargeInt %s\n", two.getValue(), one.getValue());
else if(two.compareTo(one) > 0)
System.out.printf("LargeInt %s is greater than LargeInt %s\n", two.getValue(), one.getValue());
else
System.out.printf("LargeInt %s is equal to LargeInt %s\n", two.getValue(), one.getValue());
break;
}// end switch
}while(choice != 8);
}// end main
}// end class
LargeInt Class(Custom Class We Created)
public class LargeInt implements Comparable<LargeInt>
{
private int[]myArray;
private LargeInt()
{
this("0");
}
public LargeInt(final String str)
{
this.myArray = new int[str.length()];
for(int x = 0; x < this.myArray.length; x++)
{
this.myArray[x] = Integer.parseInt(str.charAt(x)+ "");
}
}
public LargeInt add(final LargeInt passedIn)
{
String stringOne = myArray.toString();
String stringTwo = passedIn.myArray.toString();
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
return new LargeInt(""+s);
}
public void setValue(final String arrayString)
{
this.myArray = new int[arrayString.length()];
for(int x = 0; x < myArray.length; x++)
{
this.myArray[x]=arrayString.charAt(x);
}
}
#Override
public int compareTo(LargeInt passedIn)
{
if(passedIn == null)
{
throw new RuntimeException("NullExceptionError");
}
int ewu = 0;
int avs = 0;
if(this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for(int i = 0; i < this.myArray.length -1; i++)
{
if(this.myArray[i] != passedIn.myArray[i])
{
return this.myArray[i]-passedIn.myArray[i];
}
}
return ewu-avs;
}
public int hashCode()
{
String p = "";
for(int f = 0; f < this.myArray.length; f++)
{
p += myArray[f];
}
return p.hashCode();
}
public String getValue()
{
String h = "";
for(int t = 0; t < this.myArray.length; t++)
{
h += myArray[t];
}
return h;
}
#Override
public boolean equals(Object jbo)
{
if(jbo == null)
{
return false;
}
if(!(jbo instanceof LargeInt))
{
return false;
}
LargeInt k =(LargeInt)jbo;
if(k.myArray.length != this.myArray.length)
{
return false;
}
for(int d = 0; d < this.myArray.length; d++)
{
if(k.myArray[d] != myArray[d])
{
return false;
}
}
return true;
}
#Override
public String toString()
{
String c = "";
for(int q = 0; q < this.myArray.length; q++)
{
c += myArray[q];
}
return "The LargeInt is: " + c;
}
}
HW7Methods File
import java.util.*;
import java.io.*;
public class HW7Methods
{
public static String readNum(Scanner kb)
{
String num = "";
System.out.print("Enter Your Large Int: ");
num = kb.nextLine();
return num;
}
public static void displayAscendingOrder(final LargeInt first, final LargeInt second, final LargeInt third)
{
String highestInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) >= 0)
{
highestInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) >= 0)
{
highestInt = second.getValue();
}
else
{
highestInt = third.getValue();
}
String middleInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) <= 0)
{
middleInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) <= 0)
{
middleInt = second.getValue();
}
else
{
middleInt = third.getValue();
}
String lowestInt;
if(first.compareTo(second) <= 0 && first.compareTo(third) <= 0)
{
lowestInt = first.getValue();
}
else if(second.compareTo(first) <= 0 && second.compareTo(third) <= 0)
{
lowestInt = second.getValue();
}
else
{
lowestInt = third.getValue();
}
System.out.println("The LargeInts in order are: " + lowestInt + ", " + middleInt + ", " + highestInt);
}
}
MyUtil file
package MyUtils;
import java.io.*;
import java.util.Scanner;
public class MyUtil
{
public static int menu(Scanner kb)
{
int userChoice;
System.out.println("1) Print First Int");
System.out.println("2) Print Second Int");
System.out.println("3) Add Different Int");
System.out.println("4) Check If Equal");
System.out.println("5) Add Large Ints");
System.out.println("6) Display In Ascending Order");
System.out.println("7) Compare Ints");
System.out.println("8) Quit");
kb = new Scanner(System.in);
System.out.print("Please Select Your Choice: ");
userChoice = kb.nextInt();
while(userChoice < 1 || userChoice > 8)
{
System.out.print("Invalid Menu Choice. Please Re-Enter: ");
userChoice = kb.nextInt();
}
return userChoice;
}
}
When I go to run this code, it prompts me for two Large Integers like it's supposed to. However, when I choose option 5 to add them, this is what I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[I#55f96302"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at LargeInt.add(LargeInt.java:24)
at CSCD210HW7.main(CSCD210HW7.java:41)
I've never seen that type of error before. Can someone tell me what is going on?
For input string: "[I#55f96302
That is not a "proper" String you are trying to parse here.
This is what an int[] looks like when you call toString() on it.
String stringOne = myArray.toString();
Why do you do that? What is that supposed to do?
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
From the looks of it, you try to handle "large" ints with your LargeInt class by somehow storing them in an array of ints. That's okay, BigInteger also works like that (more or less), but you cannot just do calculations by trying to convert back to int (after all those numbers are too big for int arithmetic to handle, even if you do the string parsing properly).
Hey everyone so I am stuck on the last part of this program that I have been doing for an assignment. So generally I am given a large list of names and numbers that represent popularity ranks for names in certain decades. This is what the file looks like <----- this is a link to see the names.txt
So I created a method that sorts the list in a certain decade which is the getIndexOfSmallest and interchange. Every decade has two names that are ranked the same so between the years of 1900-1909 there are two names that are ranked 1, two names that are ranked 2, two names that are ranked 3 and so on. The last part of the program and the one I need help with is suppose to sort through the object array and find any decades where there is only one name for one rank or no names for a certain rank. The output will be sent to a file and it will look like this. <------ this is another link to see the expected output
This is what my code looks like. This is my Name code that creates the objects:
public class Name{
private String givenName;
private int[] ranks = new int[12];
public Name(String name, int[] popularityRanks){
givenName = name;
for (int i = 0; i < 11; i++){
ranks[i] = popularityRanks[i];
}
}
public String getName(){
return givenName;
}
public int getPop(int decade){
if (decade >= 0 && decade <= 10){
return ranks[decade];
}
else{
return -1;
}
}
public String getHistoLine(int decade){
String histoLine = ranks[decade] + ": ";
double popularity = (1000 - ranks[decade]) / 11.7;
int histo = (int)popularity;
if(popularity != 0){
for (int i = 0; i < histo; i++){
histoLine += "*";
}
}
return histoLine;
}
public String getHistogram(){
String histogram = "";
for (int i = 0; i < 11; i++){
histogram += this.getHistoLine(i) + "\n";
}
return histogram;
}
}
This is my NameApp which is where my main is at:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NameApp{
private static boolean validInput;
private static boolean stillWorking = true;
private static boolean validDecade;
private static boolean validName;
static Scanner keyboard = new Scanner(System.in);
// Main method
public static void main(String[] args) throws FileNotFoundException{
String[] nameArray = readNamesFile();
Name[] list = new Name[nameArray.length];
loadNames(list, nameArray);
char choice;
do {
do {
displayMenu();
choice = getUserInput();
} while (!validInput);
switch (choice){
case 'A':
displayHistogram(list);
break;
case 'B':
compareTwoNames(list);
break;
case 'C':
displayTopTenNames(list);
break;
case 'D':
writeAnomaliesToFile(list);
stillWorking = false;
break;
default:
break;
}
} while (stillWorking);
}
/*
* This method will read the file name names.txt and load the names and populations into a string array.
*/
private static String[] readNamesFile() throws FileNotFoundException{
String[] nameArray = new String[4429];
Scanner inputStream = null;
String fileName = "names.txt";
inputStream = new Scanner (new File(fileName));
int i = 0;
while (inputStream.hasNextLine()){
nameArray[i] = inputStream.nextLine();
i++;
}
inputStream.close();
return nameArray;
}
/*
* load names method will take a Name array and the string array from the readNamesFile method. This method will split the names and the population ranks and send them to the constructor in Name.java.
*/
private static void loadNames(Name[] list, String[] nameArray){
int length;
int spacePos;
int[] popRanks = new int[11];
String name;
String linePop;
for (int i = 0; i < nameArray.length; i++){
length = nameArray[i].length();
spacePos = nameArray[i].indexOf(" ");
name = nameArray[i].substring(0,spacePos);
linePop = nameArray[i].substring(spacePos + 1, length);
for (int j = 0; j < 11; j++){
popRanks[j] = Integer.parseInt(linePop.split(" ")[j]);
}
list[i] = new Name(name, popRanks);
}
}
/*
* displayMenu method will display the menu that the user will select their program function.
*/
private static void displayMenu(){
System.out.println("Enter the character corresponding to your selection:");
System.out.println("\ta - Print histogram for a name");
System.out.println("\tb - Compare two names in a decade");
System.out.println("\tc - Print top ten names for a decade");
System.out.println("\td - Quit (display file anomalies)");
}
/*
* getUserInput is a method that will accept a string input from the user it will send this string to two different helper methods.
*/
private static char getUserInput(){
String selection = keyboard.nextLine();
System.out.println(" Your selection: " + selection);
checkUserInput(selection);
char choice = stringToChar(selection);
return choice;
}
/*
* helper method: checkUserInput will accept the user input from getUserInput and test the input to see if the input is a valid input from the user. If it is not set the instance boolean variable to false if it is set it to true.
*/
private static boolean checkUserInput(String selection){
if (!selection.equalsIgnoreCase("a") && !selection.equalsIgnoreCase("b") && !selection.equalsIgnoreCase("c") && !selection.equalsIgnoreCase("d")){
System.out.println("Invalid input. Try again...");
return validInput = false;
}
else {
return validInput = true;
}
}
/*
* helper method: stringToChar method will take the input that the user entered after it has been tested to see if it is valid and this method will change the input to a character value. This will also make the character to an upper case letter.
*/
private static char stringToChar(String selection){
char choice = selection.charAt(0);
choice = Character.toUpperCase(choice);
return choice;
}
/*
* Menu option: A. This method will take a user input for the name they want and display the histogram for the selected name.
*/
private static void displayHistogram(Name[] list){
String nameInput;
String histogram;
int nameLocation;
do {
nameInput = nameEntry();
nameLocation = checkListArray(nameInput, list);
if (!validName){
System.out.println("The name, " + nameInput + ", was not found!");
}
} while (!validName);
histogram = list[nameLocation].getHistogram();
System.out.println("Histogram for name, " + list[nameLocation].getName() + ":");
System.out.println(histogram);
}
private static void compareTwoNames(Name[] list){
String nameOne;
String nameTwo;
String oneHistoLine;
String twoHistoLine;
int oneLocation;
int twoLocation;
int decade;
do {
nameOne = nameEntry();
oneLocation = checkListArray(nameOne, list);
if (!validName){
System.out.println("The first name, " + nameOne + ", was not found!");
}
} while (!validName);
do {
nameTwo = nameEntry();
twoLocation = checkListArray(nameTwo, list);
if (!validName){
System.out.println("The second name, " + nameTwo + ", was not found!");
}
} while(!validName);
decadeMenu();
decade = decadeSelection();
oneHistoLine = list[oneLocation].getHistoLine(decade);
twoHistoLine = list[twoLocation].getHistoLine(decade);
System.out.println("Data for " + list[oneLocation].getName());
System.out.println(" " + oneHistoLine);
System.out.println("Data for " + list[twoLocation].getName());
System.out.println(" " + twoHistoLine);
}
private static void displayTopTenNames(Name[] list){
int decade;
int count = 0;
int l = 0;
String[] decadeName = new String[20];
Name[] temp = new Name[list.length];
decadeMenu();
decade = decadeSelection();
for (int i = 0; i < list.length; i++){
temp[i] = list[i];
}
for (int index = 0; index < temp.length; index++){
int smallestIndex = getIndexOfSmallest(decade, index, temp);
interchange(decade, index, smallestIndex, temp);
}
do {
if (temp[l].getPop(decade) == 0){
l++;
}
else {
decadeName[count] = temp[l].getName() + " " + "(" + temp[l].getPop(decade) + ")";
count++;
l++;
}
} while (count < 20);
writeTopTen(decadeName, decade);
}
private static void writeAnomaliesToFile(Name[] list){
System.out.println("Terminating... but first the anomalies in the data file:");
checkAnomalies(list);
System.out.println("Anomalies written to anomalies.txt.");
}
private static String nameEntry(){
String nameInput = "";
System.out.println("Enter a name: ");
nameInput = keyboard.nextLine();
return nameInput;
}
private static int checkListArray(String nameInput, Name[] list){
int nameLocation = -1;
int listLength = list.length;
for (int i = 0; i < listLength; i++){
if (nameInput.equalsIgnoreCase(list[i].getName())){
validName = true;
return nameLocation = i;
}
}
if (nameLocation == -1){
validName = false;
return nameLocation;
}
return nameLocation;
}
private static void decadeMenu(){
System.out.println("Enter number correpsonding to your decade:");
System.out.println(" 1 - 1900-1909");
System.out.println(" 2 - 1910-1919");
System.out.println(" 3 - 1920-1929");
System.out.println(" 4 - 1930-1939");
System.out.println(" 5 - 1940-1949");
System.out.println(" 6 - 1950-1959");
System.out.println(" 7 - 1960-1969");
System.out.println(" 8 - 1970-1979");
System.out.println(" 9 - 1980-1989");
System.out.println(" 10 - 1990-1999");
System.out.println(" 11 - 2000-2005");
}
private static int decadeSelection(){
String decadeChoice;
int decade;
do {
System.out.println("Enter a decade: ");
decadeChoice = keyboard.nextLine();
decade = checkDecade(decadeChoice);
} while (!validDecade);
return decade;
}
private static int checkDecade(String decadeChoice){
int decade = 0;
try {
decade = Integer.parseInt(decadeChoice);
}
catch (Exception e){
System.out.println("That is not an integer. Please try again.");
validDecade = false;
return decade;
}
if (decade < 1 || decade > 11){
System.out.println("Enter an integer between 1 and 11");
validDecade = false;
return decade;
}
else {
validDecade = true;
decade = changeDecade(decade);
return decade;
}
}
private static int changeDecade(int decade){
int newDecade = 0;
switch (decade){
case 1:
newDecade = 0;
break;
case 2:
newDecade = 1;
break;
case 3:
newDecade = 2;
break;
case 4:
newDecade = 3;
break;
case 5:
newDecade = 4;
break;
case 6:
newDecade = 5;
break;
case 7:
newDecade = 6;
break;
case 8:
newDecade = 7;
break;
case 9:
newDecade = 8;
break;
case 10:
newDecade = 9;
break;
case 11:
newDecade = 10;
break;
default:
break;
}
return newDecade;
}
private static int getIndexOfSmallest(int decade, int startIndex, Name[] temp){
int min = temp[startIndex].getPop(decade);
int indexOfMin = startIndex;
for (int index = startIndex + 1; index < temp.length; index++){
if (temp[index].getPop(decade) < min){
min = temp[index].getPop(decade);
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int decade, int i, int j, Name[] temp){
Name tempInt = temp[i];
temp[i] = temp[j];
temp[j] = tempInt;
}
private static String decadeYears(int decade){
String decadeYear = "";
switch (decade){
case 0:
decadeYear = "1900 - 1909";
break;
case 1:
decadeYear = "1910 - 1919";
break;
case 2:
decadeYear = "1920 - 1929";
break;
case 3:
decadeYear = "1930 - 1939";
break;
case 4:
decadeYear = "1940 - 1949";
break;
case 5:
decadeYear = "1950 - 1959";
break;
case 6:
decadeYear = "1960 - 1969";
break;
case 7:
decadeYear = "1970 - 1979";
break;
case 8:
decadeYear = "1980 - 1989";
break;
case 9:
decadeYear = "1990 - 1999";
break;
case 10:
decadeYear = "2000 - 2005";
break;
default:
break;
}
return decadeYear;
}
private static void writeTopTen(String[] decadeName, int decade){
String years;
years = decadeYears(decade);
System.out.println("Ten most popular names (male and female) during the decade " + years + " were:");
for (int i = 0; i < 20; i += 2){
System.out.printf("%20s\t%20s\n", decadeName[i],decadeName[i + 1]);
}
}
private static void checkAnomalies(Name[] list){
Name[] temp = new Name[list.length];
int anomalyCount = 0;
int popTwo = 0;
int popOne = 0;
String[] anomalies = new String[list.length];
for (int i = 0; i < list.length; i++){
temp[i] = list[i];
}
for (int decade = 0; decade < 11; decade++){
for (int index = 0; index < temp.length; index++){
int smallestIndex = getIndexOfSmallest(decade, index, temp);
interchange(decade, index, smallestIndex, temp);
}
int rank = 0;
for (int i = 1; i < temp.length - 1; i += 2){
popOne = temp[i].getPop(decade);
popTwo = temp[i+1].getPop(decade);
if (popOne != 0){
rank++;
}
if (popOne == rank && popTwo != rank){
String decadeYear = decadeYears(decade);
anomalies[anomalyCount] = "One name (" + temp[i].getName() + ") for " + decadeYear + ", rank " + temp[i].getPop(decade) + ".";
anomalyCount++;
}
else if (popOne != rank && popTwo == rank){
String decadeYear = decadeYears(decade);
anomalies[anomalyCount] = "One name (" + temp[i+1].getName() + ") for " + decadeYear + ", rank " + temp[i+1].getPop(decade) + ".";
anomalyCount++;
}
else if (popOne != rank && popTwo != rank){
String decadeYear = decadeYears(decade);
anomalies[anomalyCount] = "No names for " + decadeYear + ", rank " + temp[i].getPop(decade) + ".";
anomalyCount++;
}
}
}
}
}
This is the information provided by my professor:
There are 1,065 anomalies: in some cases, only one name with a particular rank in a decade or in other cases, no names in a decade with a particular rank. With 11 decades and 999 ranks to check, 1065 is only about 9.7% of the name-pairs that are broken or anomalous. There should be a pair of names for each rank (999) in each decade (11): this gives 10,989 name-pairs. Your code to do this will need to check each name in each decade for each rank in order to find all 1065 anomalies.
When I was debugging my program I saw that the ranks end on odd numbers. which is why I started my loop in checkAnomalies at 1 instead of 0 (considering that at 0 the names rank will be 0 and that is considered to be a name that was picked 1000 or less). When I run the program with:
String[] anomalies = new String[1065];
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1065
at NameApp.checkAnomalies(NameApp.java:512)
at NameApp.writeAnomaliesToFile(NameApp.java:259)
at NameApp.main(NameApp.java:43)
and when I change my code to be:
String[] anomalies = new String[temp.length];
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4429
at NameApp.checkAnomalies(NameApp.java:502)
at NameApp.writeAnomaliesToFile(NameApp.java:259)
at NameApp.main(NameApp.java:43)
I figure my error is in my loops but I can't figure out where.. I figured my loops are finding way more errors then their really is.. Just wondering if anyone can help me out with this.. It is really the only part that I need left. Thanks in advance
EDIT:
This is the relevant code for what I need help with:
private static void writeAnomaliesToFile(Name[] list){
System.out.println("Terminating... but first the anomalies in the data file:");
checkAnomalies(list);
System.out.println("Anomalies written to anomalies.txt.");
}
method that is called:
private static void checkAnomalies(Name[] list){
Name[] temp = new Name[list.length];
int anomalyCount = 0;
int popTwo = 0;
int popOne = 0;
String[] anomalies = new String[list.length];
for (int i = 0; i < list.length; i++){
temp[i] = list[i];
}
for (int decade = 0; decade < 11; decade++){
for (int index = 0; index < temp.length; index++){
int smallestIndex = getIndexOfSmallest(decade, index, temp);
interchange(decade, index, smallestIndex, temp);
}
int rank = 0;
for (int i = 1; i < temp.length - 1; i += 2){
popOne = temp[i].getPop(decade);
popTwo = temp[i+1].getPop(decade);
if (popOne != 0){
rank++;
}
if (popOne == rank && popTwo != rank){
String decadeYear = decadeYears(decade);
anomalies[anomalyCount] = "One name (" + temp[i].getName() + ") for " + decadeYear + ", rank " + temp[i].getPop(decade) + ".";
anomalyCount++;
}
else if (popOne != rank && popTwo == rank){
String decadeYear = decadeYears(decade);
anomalies[anomalyCount] = "One name (" + temp[i+1].getName() + ") for " + decadeYear + ", rank " + temp[i+1].getPop(decade) + ".";
anomalyCount++;
}
else if (popOne != rank && popTwo != rank){
String decadeYear = decadeYears(decade);
anomalies[anomalyCount] = "No names for " + decadeYear + ", rank " + temp[i].getPop(decade) + ".";
anomalyCount++;
}
}
}
}
Solved myself just had to sleep on it:
private static void checkAnomalies(Name[] list)
throws FileNotFoundException{
Name[] temp = new Name[list.length];
String[] anomalies = new String[1065];
int anomalyCount = 0;
for (int i = 0; i < list.length; i++){
temp[i] = list[i];
}
for (int decade = 0; decade < 11; decade++){
for (int ranks = 1; ranks < 1000; ranks++){
int found = 0;
String tempName = "";
String decadeYear = decadeYears(decade);
for (int i = 0; i < temp.length; i++){
if (temp[i].getPop(decade) == ranks){
found++;
}
if (found == 1 &&
temp[i].getPop(decade) == ranks){
tempName = temp[i].getName();
}
}
if (found == 0){
anomalies[anomalyCount] = "No names "
+ "for " + decadeYear + ", rank "
+ ranks + ".";
anomalyCount++;
}
else if (found == 1){
anomalies[anomalyCount] = "One "
+ "Name (" + tempName + ") for "
+ decadeYear + ", rank "
+ ranks + ".";
anomalyCount++;
}
}
}
writeAnomaliesFile(anomalies);
}
/*
* Helper method: this method will create and write
* each anomalies to a text document called
* anomalies.txt.
*/
private static void
writeAnomaliesFile(String[] anomalies)
throws FileNotFoundException{
String fileName = "anomolies.txt";
PrintWriter outputStream = null;
outputStream = new PrintWriter(fileName);
for (int i = 0; i < anomalies.length; i++){
outputStream.println(anomalies[i]);
}
outputStream.close();
}