Why am I getting an input mismatch exception in thread "main"? - java

I marked where I got the exception and I don't know why it's happening. This code finds the popularity and meaning of a name that the user types in . It also makes a graph(but it doesn't work)
The files are too long to put on here but on line examples are: names.txt:
Brenda f 0 0 0 0 917 42 14 13 40 115 123 172 426 (popularity), meanings.txt:
BRITTANY f English From the name of the region in the northwest of France, called in French Bretagne.(meaning)
1. Why am I getting this exception?
2. How do I fix the exception?
3. Why isn't my graph drawing the bars (in method changingGraph)
Example Console Output:
Name: aaron
Aaron f 0 0 0 0 0 0 0 0 0 883 0 0 0
AARON m English, Biblical From the Hebrew name ??????? ('Aharon) which is most likely of unknown Egyptian origin.
Exception:
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 BabyNames.changingGraph(BabyNames.java:131)
at BabyNames.main(BabyNames.java:32)
my code:
import java.util.*;
import java.io.*;
import java.awt.*;
public class BabyNames{
public static final int STARTINGYEAR = 1890;
public static final int WIDTH = 60;
public static final int HEIGHT = 30;
private static String nameFinal;
private static String originalName;
public static int HEIGHTOFPANEL = 500 + (HEIGHT * 2);
public static void main(String[] args) throws FileNotFoundException{
Scanner console = new Scanner(System.in);
DrawingPanel panel = new DrawingPanel(780,HEIGHTOFPANEL);//DOES PANEL SIZE CHANGE????!?!?!?!??!?!?!?
Graphics g = panel.getGraphics(); //does there always need to be 500 free in the middle???
Scanner nameFile = new Scanner(new File("names.txt"));
Scanner meaningsFile = new Scanner(new File("meanings.txt"));
Scanner nameFile2 = new Scanner(new File("names2.txt"));
intro();
fixedGraph(g);
String nameFinal;
nameFinal = nameToLowerCase(console, originalName);//changes to correct capitalization
String meanings = "";
String popularity = "";
if(STARTINGYEAR == 1890){
popularity = findingStatistics(console,nameFile, nameFinal);
}
else{
popularity = findingStatistics(console, nameFile2, nameFinal);
}
meanings = findingStatistics(console, meaningsFile, nameFinal);
changingGraph(meanings,g,popularity); //EXCEPTION HERE
}
//prints introduction to what the program does
public static void intro(){
System.out.println("This program allows you to search through the");
System.out.println("data from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since" + STARTINGYEAR );
System.out.println();
System.out.print("Name: ");
}
//Converts what the user types in so the first letter is
//capitalized and the rest is lower case
public static String nameToLowerCase(Scanner console, String originalName){
originalName = console.next();
String name = "" ;
int lengthOfName = originalName.length();
String beginingOfName = originalName.substring(0,1).toUpperCase();
String endOfName = originalName.substring(1,lengthOfName).toLowerCase();
name = beginingOfName + endOfName;
return name;
}
public static String findingStatistics(Scanner console, Scanner data, String nameFinal){
boolean goesThroughOnce = false; //
String statistics = "";
String currWord = "";
String currLine = "";
while (data.hasNext() && goesThroughOnce == false){
currLine = data.nextLine();
Scanner lineBeingRead = new Scanner(currLine); //make other scanners?? for each file
currWord = lineBeingRead.next(); //
if (currWord.equals(nameFinal) || currWord.equals(nameFinal.toUpperCase())){ //
statistics = currLine;
goesThroughOnce = true;
System.out.println(statistics);
}
else{
}
}
if(goesThroughOnce == false){
System.out.print(originalName + " not found"); //ASK ABOUT THE EXCEPTION
}
return statistics;
}
public static void fixedGraph(Graphics g){ //Draws fixed things such as gray blocks and black lines
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,780,HEIGHT);
g.fillRect(0,HEIGHTOFPANEL-HEIGHT,780,HEIGHT);
g.setColor(Color.BLACK);
g.drawLine(0,HEIGHT,780,HEIGHT);
g.drawLine(0,HEIGHTOFPANEL-HEIGHT,780,HEIGHTOFPANEL-HEIGHT);
}
public static void changingGraph(String meanings, Graphics g, String popularity){
g.drawString("" + meanings,0,16); //draws meaning text
int startingYear = STARTINGYEAR;
int amountOfDecades = 0;
if(startingYear == 1890){
amountOfDecades = 13;
}
else{
amountOfDecades = 8;
}
// g.drawString("" + startingYear,0,552); //fencepost
for(int i=0; i<=amountOfDecades;i++){
int year = startingYear + (10 * i);
g.drawString("" + year,(WIDTH*i),HEIGHTOFPANEL-8); //draws decade numbers
}
Scanner popularityData = new Scanner(popularity);
Scanner meaningsData = new Scanner(meanings);
String currChar = popularityData.next();
boolean gender = false; //if it is a boys name
boolean stop = false;
while(meaningsData.hasNext() && stop == false){//determines which color the bars will be
if(currChar.equals("f")){
gender = true;
}
if(gender == true){
g.setColor(Color.PINK);
stop = true;
}
else{
currChar = meaningsData.next();
}
}
if(stop ==false){
g.setColor(Color.BLUE);
}
int ranking;
while(popularityData.hasNext() && stop == false){ //EXCEPTION HERE
ranking = popularityData.nextInt();
for(int i=0; i<=amountOfDecades;i++){
g.fillRect(WIDTH*i,(ranking/2)+30,WIDTH/2,(560-HEIGHT*2)-((ranking/2)+30) );
g.drawString("" + ranking, WIDTH*i, (ranking/2)+30);
}
}
}
}

Related

I want to know why the program worked in eclipse but was not able to submit in Codejam

I tried to attend in google code jam and in qualification round when I submit it I got WA(Wrong Answer). When it worked fine in my eclipse can I know the problem with my code so I can fix my code. I also got the correct output when I tried to test my program with sample input and output.
Input
4
3
360 480
420 540
600 660
3
0 1440
1 3
2 4
5
99 150
1 100
100 301
2 5
150 250
2
0 720
720 1440
Output
Case #1: CJC
Case #2: IMPOSSIBLE
Case #3: JCCJJ
Case #4: CC
import java.util.Scanner;
public class Solution {
public static void main(String args[]) {
int T=0;
Scanner a = new Scanner(System.in);
T = a.nextInt();
int cases=0;
String work[][] = new String[T][1000];
String data[] = new String[T];
while(T>cases) {
//System.out.println("cases: "+cases);//debug
int N=a.nextInt();
int J[][] = new int[N][2];
int C[][] = new int[N][2];
for(int i=0;i<N;i++) {
//System.out.println("For : i"+ i);//debug
int Si = a.nextInt();
int Ei = a.nextInt();
boolean check = true;
boolean check1 =true;
for(int k=0;k<i;k++) {
if(Si>=J[k][0]&&Si<J[k][1]) {
check=false;
}
if(Ei>J[k][0]&&Ei<=J[k][1]) {
check=false;
}
if(Si>=C[k][0]&&Si<C[k][1]) {
check1=false;
}
if(Ei>C[k][0]&&Ei<=C[k][1]) {
check1=false;
}
}
if(check) {
//System.out.println("Upgrade1");
J[i][0] = Si;
J[i][1] = Ei;
work[cases][i] = "J";
}else if(check1) {
//System.out.println("Upgrade2");
C[i][0] = Si;
C[i][1] = Ei;
work[cases][i] = "C";
}else
work[cases][i]= "I";
}
for(int k=0;k<N;k++) {
//System.out.println("N: "+ N);
if(k==0)
data[cases] = work[cases][k];
else
data[cases]+=work[cases][k];
}
cases++;
}
for(int k=0;k<T;k++) {
if(data[k].contains("I")) {
data[k]="Impossible";
}
}
for(int i=0;i<T;i++) {
//System.out.println("Printing");
System.out.println("Case #" + (i+1) + ": "+ data[i]);
}
}
}

Unable to calculate discount

Hey everyone so I'm new to programming and recently I've been introduced to array's I've been having some problems in my current project. Essentially I am getting an array out of bounds exception when trying to calculate the discount price (afterDiscount located at the bottom) however when I run the program I get this error. I'm not sure how to fix it as I have not dealt with arrays before.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at StarterJ52PartPriceDiscount.main(StarterJ52PartPriceDiscount.java:108)
import java.io.*;
import java.util.*;
public class StarterJ52PartPriceDiscount
{
public static void main(String[] args) throws FileNotFoundException
{
// Constants
final int MAX = 30; // max records on parts.dat
final int SENTINEL = 999;
// File Objects - Parts and Trans files
Scanner inPartsFile = new Scanner(new FileReader("parts.dat"));
Scanner inTransFile = new Scanner(new FileReader("trans.dat"));
// Part file Variables
int stkPartNo;
double stkPartPrice; // ???
// Tx file Variables
int txPartNo;
int txQuantity;
int txDiscountCode;
// Arrays
int[] partNos = new int[MAX];
double[] prices = new double[MAX];
int[] discounts = {0,5,10,15,20,25,30,40,50}; // Discount Percentages
// Other Variables
Scanner console = new Scanner(System.in);
int recCount; // no records on file
int cnt, foundPosition,i,pos; // index
double beforeDiscount, afterDiscount, totalDiscount, cost;
boolean found;
// Initialise
recCount = 0;
foundPosition = 0;
totalDiscount = 0;
found = false;
pos =-1;
// Output Part No and Prices (for)
System.out.println("Part No Part Price");
for(i=0; i <MAX; i++)
{
stkPartNo = inPartsFile.nextInt();
stkPartPrice = inPartsFile.nextDouble();
//System.out.printf("%2d %4.2f %n",stkPartNo,stkPartPrice );
partNos[i] = stkPartNo;
prices[i] = stkPartPrice;
System.out.printf("%6d %7.2f %n",partNos[i],prices[i]);
}//for
// Initial Tx read of first record
txPartNo=inTransFile.nextInt();
System.out.println("Part Quantity Disc Code");
while(txPartNo != SENTINEL)
{
txQuantity = inTransFile.nextInt();
txDiscountCode = inTransFile.nextInt();
System.out.printf("%4d %4d %4d %n",txPartNo,txQuantity,txDiscountCode );
txPartNo=inTransFile.nextInt();
}//While
// Verify Tx trans.dat contents (initially)
inTransFile.close();
inTransFile = new Scanner(new FileReader("trans.dat"));
System.out.println("xxxxxxx");
txPartNo=inTransFile.nextInt();//initial Read
while(txPartNo != SENTINEL)
{
txQuantity = inTransFile.nextInt();
txDiscountCode = inTransFile.nextInt();
System.out.printf("%4d %4d ",txPartNo,txQuantity );
found = false;
pos = -1;
while (pos < partNos.length -1 && found == false)
{
++pos;
if (partNos[pos] == txPartNo){
found = true;
}
else if (partNos[pos] > txPartNo){ // Ordered
pos = partNos.length; // break;
}
} // inner while
if (found) { // == true
beforeDiscount = prices[pos];
//Throws out of bounds exeption
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode]);
System.out.printf("%4.2f %n",beforeDiscount);
System.out.printf("%4.2f %n",afterDiscount);
}
else {
System.out.println("NOT Found");
}//if
txPartNo=inTransFile.nextInt();//Sub Read
}//While
} // main
}
ThankYou for your comments I was able to rectify the problem, my discount array was beginning at position 1 rather than position 2, therefore, cause the out of bounds exception
changed the code from this
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode]);
to this
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode-1]);

Java NameLengthNotValidException always gets thrown in domainclass

IMPORTANT: Probably a rookie question, but I'm clueless on how to solve it.
I have a UI class which I use to input a name and gender (geslacht) using a scanner (see code below)
private static void geefNaamEnGeslacht(int aantal) {
String naam, geslacht;
for (int i = 0; i < aantal; i++) {
System.out.print("Wat is de naam van speler " + (i + 1) + " (min 6 tekens, max 12 tekens)? ");
naam = sc.next();
naam += sc.nextLine();
System.out.print("Wat is het geslacht van speler " + (i + 1) + "(man=m vrouw=v)? ");
geslacht = sc.next();
System.out.println(naam.length());
try {
dc.maakSpelerAan(naam, geslacht.charAt(0));
} catch (NameLengthNotValidException e) {
System.out.println(e.getMessage());
i--;
}
}
}
In my domain class I check the length of that name in the setter, but it always throws the exception, no matter what I tried. When debugging, the length of any name I picked checks out to be between 6 and 12 characters strangely enough. (see code below)
public final void setNaam(String naam) {
int lengte = naam.length();
if (naam.length() < 6 || naam.length() > 12) {
throw new NameLengthNotValidException("Je naam moet tussen 6 en 12 tekens liggen!");
}
this.naam = naam;
}
Any ideas or tips are apreciated.
EDIT1 code of dc.maakSpelerAan
public void maakSpelerAan(String naam, char geslacht){
s.maakSpeler(naam, geslacht);
}
EDIT2 code of s.maakspeler
public void maakSpeler(String naam, char geslacht){
if (spelCompleet()) {
throw new ListFilledException("De lijst met spelers is vol !");
}
if (!controleerUniekeNaam(naam)) {
throw new NotUniqueNameException();
}
Kaart[] schatkaarten = new Kaart[STARTAANTAL];
Kaart[] kerkerkaarten = new Kaart[STARTAANTAL];
for (int i = 0; i > STARTAANTAL; i++) {
schatkaarten[i] = stapels.get(SCHATKAART).geefBovensteKaart();
kerkerkaarten[i] = stapels.get(KERKERKAART).geefBovensteKaart();
}
try{
Speler s = new Speler(naam, geslacht);
s.getKaarten(kerkerkaarten, schatkaarten);
spelers.add(s);
}catch (IllegalArgumentException | NameLengthNotValidException e){
throw e;
}
if (spelCompleet()) {
//UC2
spelers.get(EERSTESPELERINDEX).setBeurt(true);
}
}
EDIT3 REPOST WITH CORRECT IMAGE Image of variable "naam" right before it goes in the IF loop while debugging. MINLENGTHNAAM and MAXLENGTHNAAM are set to 6 and 12 respectively in an interface class.
EDIT4 Code in my interface class for MINLENGTH AND MAXLENGTH
public interface SpelInfo {
final int STARTAANTAL = 2;
final int MAXAANTALPUNTEN = 10;
final int INDEXNAAMDETAILS = 0;
final int INDEXGESLACHTDETAILS = 1;
final int INDEXPUNTENDETAILS = 2;
final int MINAANTALSPELERS = 3;
final int MAXAANTALSPELERS= 6;
final int EERSTESPELERINDEX = 0;
final int MAXLENGTHNAAM = 6;
final int MINLENGTHNAAM = 12;
final int AANTALSTAPELS = 2;
final char MAN = 'm';
final char VROUW = 'v';
final int SCHATKAART = 0;
final int KERKERKAART = 1;
}
In "Edit4" you need to change the green line into:
if(naam.length() > MAXLENGTHNAAM || naam.length() < MINLENGTHNAAM) {
Just a little logical issue :)

Loop is skipping statement (CASINO PROGRAM)

I'm trying to make a casino program for my school project. Everything seems to work just fine except that the statement of the do-while loop inside the main() method is always skipped at the first, third, fifth (odd) lines in the console.
THE PROGRAM:
import java.util.Scanner;
import java.text.*;
import java.util.*;
public class Casino
{
public static Scanner input;
static final String SEPARATOR = "\n";
public static void main (String[] args) throws Exception
{
int winnings;
while (getBet() != 0)
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * getBet();
display(thePull, winnings);
}
System.out.println("Thanks");
}
//gets bet, stores in static class variables
public static int getBet()
{
final double MAX_BET = 50;
String prompt, strUserResponse;
int intResponse;
input = new Scanner(System.in);
do
{
prompt = "How much would you like to bet ( Min $1 - Max $50 ) "
+ "or press '0' to quit?";
System.out.print(prompt);
strUserResponse = input.nextLine();
intResponse = Integer.parseInt(strUserResponse);
}
while( intResponse < 0 || intResponse > MAX_BET );
return intResponse;
}
public static String randString()
{
int bar = 38;
int cherries = 78;
int space = 85;
int seven = 100;
String randomString = "";
int randomNum = 1 + (int)(Math.random() * 100);
if (randomNum <= bar)
randomString = "BAR";
else if (randomNum <= cherries)
randomString = "cherries";
else if (randomNum <= space)
randomString = "space";
else if (randomNum <= seven)
randomString = "7";
return randomString;
}
public static TripleString pull()
{
TripleString pullString = new TripleString();
String str1 = randString();
pullString.setString1(str1);
String str2 = randString();
pullString.setString2(str2);
String str3 = randString();
pullString.setString3(str3);
return pullString;
}
public static int getPayMultiplier (TripleString thePull)
{
if (thePull.getString1() == "cherries" &&
thePull.getString2() != "cherries" )
return 5;
else if (thePull.getString1() == "cherries" &&
thePull.getString2() == "cherries" &&
thePull.getString3() != "cherries")
return 15;
else if (thePull.getString1() == "cherries" &&
thePull.getString2() == "cherries" &&
thePull.getString3() == "cherries")
return 30;
else if (thePull.getString1() == "BAR" &&
thePull.getString2() == "BAR" &&
thePull.getString3() == "BAR")
return 50;
else if (thePull.getString1() == "7" &&
thePull.getString2() == "7" &&
thePull.getString3() == "7")
return 100;
else
return 0;
}
public static void display (TripleString thePull, int winnings)
{
System.out.println(SEPARATOR + ">>>Brrrrrr! Your Pull Is . . .<<<"
+ SEPARATOR + thePull.toString());
if ( winnings == 0)
System.out.println("Sorry you lose. . . GOOD LUCK NEXT TIME!"
+ SEPARATOR);
else
System.out.println("Congaratulations, you win =" + " $" + winnings
+ " !" + SEPARATOR + "YEAY !!! :):):)" + SEPARATOR);
}
}
class TripleString
{
//member data
private String string1, string2, string3;
//static constants
public static final double MIN_LEN = 1;
public static final double MAX_LEN = 50;
public static final String DEFAULT_STRING = "undefined";
//default constructor
TripleString ()
{
string1 = DEFAULT_STRING;
string2 = DEFAULT_STRING;
string3 = DEFAULT_STRING;
}
//parameter-taking constructor
TripleString (String str1, String str2, String str3)
{
if (! setString1(str1))
str1 = DEFAULT_STRING;
if (! setString2(str2))
str2 = DEFAULT_STRING;
if (! setString3(str3))
str3 = DEFAULT_STRING;
}
//private static helper method
private boolean validString(String str)
{
if (str == null || str.length() < MIN_LEN || str.length() > MAX_LEN)
return false;
else
return true;
}
//accessor set methods
public boolean setString1 (String stringName1)
{
if ( !validString(stringName1) )
return false;
string1 = stringName1;
return true;
}
public boolean setString2 (String stringName2)
{
if ( !validString(stringName2) )
return false;
string2 = stringName2;
return true;
}
public boolean setString3 (String stringName3)
{
if ( !validString(stringName3) )
return false;
string3 = stringName3;
return true;
}
//accessor get methods
public String getString1 () { return string1; }
public String getString2 () { return string2; }
public String getString3 () { return string3; }
public String toString ()
{
String reStr;
reStr = string1 + " "+ string2 + " " + string3;
return reStr;
}
}
Here is the example of my run:
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?1
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?6
//Brrrrr below supposed to have ">>>" "<<<" but I remove it manually in this example since it creates blockquotes
Brrrrrr! Your Pull Is . . .
cherries cherries BAR
Congaratulations, you win = $90 !
YEAY !!! :):):)
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?7
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?7
Brrrrrr! Your Pull Is . . .
7 BAR cherries
Sorry you lose. . . GOOD LUCK NEXT TIME!
I want to make it looks more like
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?1
Brrrrrr! Your Pull Is . . .<<<
BAR BAR BAR
Congaratulations, you win = $50 !
YEAY !!! :):):)
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?2
Brrrrrr! Your Pull Is . . .<<<
BAR cherries BAR
Sorry you lose. . . GOOD LUCK NEXT TIME!
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?0
I think the problem has to be related with the loop in my getInput() method, but I'm really not sure why. I know I could've not make a loop in the getInput() method, but my instructor specifies that the method has to loop until the user put the valid #(1-50)
I've tried changing it to the standard while loop or modifying the code in many other way, but in new ways come new problems. For example, if I change my main method to
Alternate main()
public static void main (String[] args) throws Exception
{
int bet = getBet(), winnings;
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
}
while (getBet() != 0);
System.out.println("Thanks");
}
If I use the above code for the main, my variable bet will stay the same for every loop since it has been initiated before that.
Edit: the alternate main() method
Edit2: Add more sample run
Your second main does not work, because you do not re-assign the bet variable.
Working simple alternate main()
public static void main (String[] args) throws Exception
{
int bet = getBet(), winnings;
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
bet = getBet();
}
while ( bet != 0);
System.out.println("Thanks");
}
Your first main does not work because you call getBet() twice
Working main
public static void main (String[] args) throws Exception
{
int winnings;
int bet;
while ((bet = getBet()) != 0)
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
}
System.out.println("Thanks");
}
If you want your bet variable to not remain the same, you can change the while loop to simply:
while(true){
//get the bet here
if(bet == 0){
break;
}
//Do the rest of your stuff here.
}
This will change the bet every iteration but still stop running if it is zero.

File/Variable Error Java

This code looks through hundreds of names and finds the popularity and meaning of them. I have two questions. what I am trying to accomplish where the error is, is to print text of the meaning of the name on to the top of my graph.
1. How can I fix this error:
BabyNames.java:82: error: cannot find symbol
String meanings = findingStatistics(console,meaningsFile);
2. By the time findingStatistics runs through twice, variable statistics is only holding the information for the meaning of the name. How can I access the popularity of the name to use my graph? Right now I have the whole method equal to the statistics, which is just the meaning.
Here is my code:
import java.util.*;
import java.io.*;
import java.awt.*;
public class BabyNames{ //ADD COMMENTS
public static final int STARTINGYEAR = 1890;
public static final int WIDTH = 60;
public static final int HEIGHT = 30;
private static String nameFinal;
public static void main(String[] args) throws FileNotFoundException{
Scanner console = new Scanner(System.in);
DrawingPanel panel = new DrawingPanel(780,560);
Graphics g = panel.getGraphics();
Scanner nameFile = new Scanner(new File("names.txt"));
Scanner meaningsFile = new Scanner(new File("meanings.txt"));
Scanner nameFile2 = new Scanner(new File("names2.txt"));
intro();
fixedGraph(g);
nameFinal = nameToLowerCase(console);
if(STARTINGYEAR == 1890){
findingStatistics(console,nameFile);;
changingGraph(console,g);
}
else{
findingStatistics(console, nameFile2);
changingGraph(console,g);
}
findingStatistics(console,meaningsFile);
}
public static void intro(){
System.out.println("This program allows you to search through the");
System.out.println("data 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();
System.out.print("Name: ");
}
public static String nameToLowerCase(Scanner console){
String originalName = console.next();
String name = "" ;
int lengthOfName = originalName.length();
String beginingOfName = originalName.substring(0,1).toUpperCase();
String endOfName = originalName.substring(1,lengthOfName).toLowerCase();
name = beginingOfName + endOfName;
return name;
}
public static String findingStatistics(Scanner console, Scanner data){
// String nameFinal = nameToLowerCase(console);
boolean goesThroughOnce = false; //
String statistics = "";
String currWord = "";
String currLine = "";
while (data.hasNext() && goesThroughOnce == false){
currLine = data.nextLine();
Scanner lineBeingRead = new Scanner(currLine); //make other scanners?? for each file
currWord = lineBeingRead.next(); //
if (currWord.equals(nameFinal) || currWord.equals(nameFinal.toUpperCase())){ //
statistics = currLine;
goesThroughOnce = true;
System.out.println(statistics);
}
else{
}
}
return statistics;
}
public static void fixedGraph(Graphics g){ //Draws fixed things such as gray blocks and black lines
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,780,HEIGHT);
g.fillRect(0,560-HEIGHT,780,HEIGHT);
g.setColor(Color.BLACK);
g.drawLine(0,HEIGHT,780,HEIGHT);
g.drawLine(0,560-HEIGHT,780,560-HEIGHT);
}
public static void changingGraph(Scanner console, Graphics g){
String meanings = findingStatistics(console,meaningsFile);
g.drawString("" + meanings,0,16); //draws meaning text
int startingYear = STARTINGYEAR;
int amountOfDecades = 0;
if(startingYear == 1890){
amountOfDecades = 13;
}
else{
amountOfDecades = 8;
}
g.drawString("" + startingYear,0,552); //fencepost
for(int i=0; i<=amountOfDecades;i++){
int year = startingYear + (10 * i);
g.drawString("" + year,(WIDTH*i),552); //draws decade numbers
}
}
}
If I add a // on what the error was and not include that, just so one can understand the code better, for the name "Aaron" it should print out:
Name: AARON
Aaron f 0 0 0 0 0 0 0 0 0 883 0 0 0
AARON m English, Biblical From the Hebrew name ??????? ('Aharon) which is most likely of unknown Egyptian origin.
Shortly, I'm trying to make it print text on the graph, and making two variables for the meaning and popularity (I have them both under statistics).
Your changingGraph method is only using console in order to work out meanings, for which of course, it also needs meaningsFile. It would make far more sense to remove the call to findingStatistics from changingGraph, especially since you are calling it from main anyway.
So change the signature of changingGraph so that it takes meanings as a parameter, as well as removing the first line of the method body. It will then look like this.
public static void changingGraph(String meanings, Graphics g){
g.drawString("" + meanings,0,16); //draws meaning text
// ... and so on.
Then, when you call it, pass the value that was returned from the previous call to findingStatistics. So in your main method, you'll have this.
if(STARTINGYEAR == 1890){
findingStatistics(console,nameFile);
}
else{
findingStatistics(console, nameFile2);
}
String meanings = findingStatistics(console, meaningsFile);
changingGraph(meanings, g);

Categories

Resources