I having some trouble with an APCS assignment. The program is supposed to read strings with a length of two from a text file - test1.txt - and print out percentages of: a) girl-girl, boy-boy, boy-girl or girl-boy combinations, and b) the total number of individual groups.
I've been trying for an hour to figure this out! Although I'm suspicious of the String declaration in line 25, I don't have a way to confirm that. Furthermore, I'm worried that I messed up my if-else-if-else loop without prompting a compiler error.
The source code is attached for your reference. If you need any additional information, please don't hesitate to ask.
Since I'm a new user with a reputation < 10, please see the attached image:
For elaboration on what isn't working. I took a screenshot and wrote relevant comments on it!
/**
* Family takes user input of sets of boys, girls, and boys + girls. Results are then
* tabulated and displayed in a percentage form to the user. The total number of
* individuals are also displayed.
*
* #E. Chu
* #Alpha
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family {
public static void main (String[] args) throws IOException {
int boyCount = 0;
int girlCount = 0;
double boyGroupCount = 0.0;
double girlGroupCount = 0.0;
int mixedGroupCount = 0;
int totalPersonCount = 0;
double totalGroupCount;
String currentToken = " ";
Scanner inFile = new Scanner (new File ("test1.txt"));
while (inFile.hasNextLine()) {
currentToken = inFile.nextLine( );
if (currentToken == "BG") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "GB") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "BB") {
boyCount += 2;
boyGroupCount++; }
else {
girlCount += 2;
girlGroupCount++; }
}
inFile.close();
totalPersonCount = boyCount + girlCount;
totalGroupCount = boyGroupCount + girlGroupCount + mixedGroupCount;
System.out.println("Sample Size: " + totalPersonCount);
System.out.println("Two Boys (%): " + boyGroupCount / totalGroupCount + "%");
System.out.println("One Boy, One Girl (%): " + mixedGroupCount + "%");
System.out.println("Two Girls (%): " + girlGroupCount / totalGroupCount + "%");
} // End of main method.
} // End of class Family.
currentToken == "BB" should be currentToken.equals("BB")
Don't use == use the method equals instead
Hint: you don't want to compare strings using ==, look into the equals method.
Related
First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n
So I just whipped up this quick little demo game in like 30 minutes and I was wondering 2 things:
How could I organize my code more?
Would you be willing to play a game like this?
I know that I could use classes but I'm a bit inexperienced them. I'm confused on how to get variables from specific classes. Would I need to import them into the main method class?
import java.util.Scanner;
public class mainGame
{
public static Scanner kboard = new Scanner(System.in);
public static boolean loop = true;
public static int treesInArea = 0;
public static int day = 0;
public static int wood = 0;
public static int woodCollected = 0;
public static int woodLevel = 0;
public static void main(String[] args)
{
System.out.println("__________________________________");
System.out.println(" Welcome to seul...Lets begin ");
System.out.println(" You woke up in the middle of ");
System.out.println(" a forest. Use the command walk ");
System.out.println(" in order to walk into a new area ");
System.out.println("__________________________________\n");
while(loop == true)
{
String choice = kboard.nextLine();
if(choice.equalsIgnoreCase("walk"))
{
treesInArea = (int)(Math.random() * 20);
System.out.println("__________________________________");
System.out.println("The number of trees in this area is");
System.out.println(treesInArea + " trees");
System.out.println("__________________________________\n");
day++;
System.out.println(" It is day " + day + " ");
System.out.println("__________________________________\n");
System.out.println(" Current usuable commands are : ");
System.out.println(" - Chop tree\n");
} else
if(choice.equalsIgnoreCase("choptree") || choice.equalsIgnoreCase("chop tree"))
{
if(treesInArea < 1)
{
System.out.println("There are no trees in this area.");
} else
{
woodCollected = (int)(Math.random() * 10);
treesInArea --;
wood += woodCollected;
woodLevel += (int)(Math.random() * 2);
System.out.println("__________________________________");
System.out.println(" You collected " + woodCollected + " wood");
System.out.println(" Your total wood = " + wood);
System.out.println(" Your total woodcutting level = " + woodLevel);
System.out.println("__________________________________\n");
}
}
}
}
}
You could improve your code in 4 main ways:
1 • Your code-indentation is not great, it should be a 4 space(or just press tab) indent after class name, loops, if statements etc. Example:
private methodName() {
for(int i = 0; i < 10; i++;) {
//do something
}
}
2 • It is easier to read your code when braces are right after methods/loops, and it takes less space, such as(5 lines of neat code):
if (condition = true) {
//do something
} else {
//do something else
}
Rather than(7 lines of messy code):
if (condition = true)
{
//do something
} else
{
//do something else
}
because when you have long if-else blocks, or long loops, it can become hard to read.
3 • You do not need to add spaces after a line, this does nothing. So this:
System.out.println(" It is day " + day + " ");
Can become this:
System.out.println(" It is day " + day);
4 • Lastly, the best way to organize code is by "dividing and conquering". This means make methods even if they're very short, to prevent repeat-code and save time. For example, you printed this line: System.out.println("__________________________________"); 7 times in your program. If you make a method like the one below, you can save time and space, by avoiding repeat-code, and simply call the method using printDivider(); wherever you used this line:
private static void printDivider() {
System.out.println("__________________________________");
}
Yes, I would play your game(in fact i did play your game), but you could improve it, by adding more possibilities, or different 'paths' to go down, ending in different results.
This code is supposed to read the csv file, use an array to add all the Axillary (Array[2]) together and find an average.
The only twist is that the IF statement is used because I want to split the data to two different variables depending on the value of (Array[3]) which will be either 1 or 2. and find the averages of them separately.
When i run this code, the output value is 0 for both.
package javainputoutput;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class JavaInputOutput
{
public static void main(String[] args)
{
int totalOverAxillary = 0;
int countOverAxillary = 0;
int totalLessAxillary = 0;
int countLessAxillary = 0;
String fileName = "haberman.txt";
try
{
Scanner InputStream = new Scanner(new File(fileName));
while (InputStream.hasNextLine())
{
String line = InputStream.nextLine();
String[] ary = line.split(",");
int noPosAxillary = Integer.parseInt(ary[2]);
int survivalStatus = Integer.parseInt(ary[3]);
if(survivalStatus == 1)
{
totalOverAxillary =+ noPosAxillary;
countOverAxillary++;
}
else if(survivalStatus == 2)
{
totalLessAxillary =+ noPosAxillary;
countLessAxillary++;
}
}
InputStream.close();
int aveOverAxillary = totalOverAxillary / countOverAxillary;
int aveLessAxillary = totalLessAxillary / countLessAxillary;
System.out.print("The average number of positive axillary nodes "
+ "for patients that survived 5 years or longer is "
+ aveOverAxillary);
System.out.println();
System.out.print("The average number of positive axillary nodes "
+ "for patients that died within 5 years is "
+ aveLessAxillary);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + fileName);
}
catch(IOException e)
{
System.out.println("Problem with input from file " + fileName);
}
}
}
It seems you messed up the += operator. Instead of this:
totalOverAxillary =+ noPosAxillary;
It should be this:
totalOverAxillary += noPosAxillary;
You have the above mistake in two places, make sure to fix both.
The effect of this is that the total values will be equal to the last values, instead of the sums.
And when you divide those values by the counts,
probably the counts are smaller than the values,
and integer division results in zeros.
I'm new to java and I'm banging my head against a wall with a task. I need to get this to work. Can anyone tell me where I went wrong? I need to write an application for Carl’s Carpentry that shows a user a list of available items: table, desk, dresser, or entertainment center. Allow the user to enter a string that corresponds to one of the options, and display the price as $250, $325, $420, or $600, accordingly. Display an error message if the user enters an invalid item. The program MUST contain parallel arrays.
import javax.swing.*;
public class CarpentryChoice
{
public static void main(String[] args)
{
String entry;
String [] item = {"table","desk","dresser","entertainment center"};
int [] price = {250, 325, 420, 600};
String strPiece;
int x, fi = 99;
String prompt = "Please select an item\n" +
"Our furniture is:\n" + "Table\n" +
"Desk\n" +
"Dresser\n" +
"Entertainment center\n" +
"Enter an item letter";
entry = JOptionPane.showInputDialog(null, prompt);
entry = strPiece.ToString();
for(x = 0; x < item.length; ++x)
if(strPiece == item[x])
fi = x;
if(fi == 99)
JOptionPane.showMessageDialog(null,
"Invalid item code entered");
else
{
if (fi > 2)
fi = fi - 3;
JOptionPane.showMessageDialog(null, "Furniture item " +
strPiece + " is priced at $" +
price[fi]);
}
System.exit(0);
}
}
Any help is MUCH appreciated!!
Thanks!
It is toString instead of ToString.
Why are you assigning entry twice? The second assignment will override what the user input via the prompt dialog. You don't need the variable strPiece in this case. You can just use entry:
entry = JOptionPane.showInputDialog(null, prompt);
for(x = 0; x < item.length; ++x)
To compare Strings, use the equals instead of the == operator:
if(entry.equals(item[x]))
And in the part that displays the result dialog, use entry again instead of strPiece (simply remove strPiece from the entire code):
JOptionPane.showMessageDialog(null, "Furniture item " +
entry + " is priced at $" +
price[fi]);
I'm new to Java, and struggling with something I've never had trouble with in the past. For whatever reason, I can't scan an int (or a double) in my code, but I can scan a string just fine. I'm posting the snippet where my scanner isn't functioning, please let me know if I should include the rest of the program.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class DZP3
{
public static void main(String[] args) throws IOException
{
announce();
Scanner scan = new Scanner(System.in);
//Prompt user for input file
System.out.println("Greetings! Please enter the filename of the plaintext olympics data file you'd like to open.");
String txtFilename = scan.nextLine();
//Opens olympics data txt file specified, exits if it does not exist
File medalsInput = new File (txtFilename);
if(!medalsInput.exists())
{
System.out.println("File not found. Reload and try again.");
System.exit(1);
}
//Prompt user for output file
System.out.println("Thanks. Please enter the filename of the plaintext data output file.");
String outputTxt = scan.nextLine();
//Create output file specified
File medalsOutput = new File (outputTxt);
//Prompt user for medal cutoff X value
System.out.println("Thanks. Please enter the minimum number of medals a nation must have earned to be counted for calculation 2 listed above. \nEnter the value, as an integer:");
int medalsCutoff = 0;
medalsCutoff = scan.nextInt();
fileProcessing(medalsInput, medalsOutput, medalsCutoff);
}
}
Near the bottom, medalsCutoff is not accepting any scanned value whatsoever. I've tried putting it in a method other than main, I've tried rearranging it, creating a separate scanner just for it, and a few other things. The debugger shows that, no matter what, I'm stuck on that line of code. What have I done wrong? I'm at a loss.
EDIT: Here's the fileProcessing method, and what comes after. The announce method is just system.out.println.
public static void fileProcessing(File medalsIn, File medalsOut, int medalsMin) throws IOException
{
//Initialize necessary variables and strings
int maxTotMedals = -1;
int natCountMedalsMin = 0;
int natHiScore = -1;
String natName;
String answerOne = "DEFAULT";
int answerTwo = 0;
String answerFour = "DEFAULT";
//Create Printwriter
PrintWriter pw = new PrintWriter(medalsOut);
//Create scanner to read from file, loop until end of file
Scanner filescan = new Scanner(medalsIn);
while (filescan.hasNext())
{
//Initializes medal counting variables at zero, resetting the values with each line
int gCount = 0;
int sCount = 0;
int bCount = 0;
natName = filescan.next();
int lineMedals = 0;
while (lineMedals < 4); //Runs 4 times to cover all four years
{
gCount += filescan.nextInt();
sCount += filescan.nextInt();
bCount += filescan.nextInt();
lineMedals++;
}
int totalMedals = gCount + sCount + bCount;
//Sees if this line's medals have exceeded previous total medal record, if yes, sets country name as answer to question one
if (totalMedals > maxTotMedals)
{
answerOne = natName;
maxTotMedals = totalMedals;
}
if (totalMedals >= medalsMin)
{
natCountMedalsMin++; //For answer two
}
//Score calculation
int natScore = gCount*3;
natScore += sCount*2;
natScore += bCount;
//Compares score to highest score, for answer four
if (natScore > natHiScore)
{
answerFour = natName;
natHiScore = natScore;
}
//Write nation name and score to file
pw.println(natName + " " + natScore);
}
//Define answer two after all countries have been counted
answerTwo = natCountMedalsMin;
//Close output file
pw.close();
//Send results to answer method
answerPrint(answerOne, answerTwo, answerFour, medalsMin, natHiScore);
}
//This method outputs the answers to the user.
public static void answerPrint(String answerEin, int answerZwei, String answerVier, int medalsMini, int HiScore)
{
System.out.println("File read successfully.");
System.out.println("The nation that earned the greatest number of medals is " + answerEin + ".");
System.out.println(answerZwei + " countries earned more than " + medalsMini + " medals.");
System.out.println("The nation with the highest score is " + answerVier + " with a score of " + HiScore + ".");
System.out.println("Thank you for using this program. Until next time!");
}
EDIT 2: This has been solved, I had a stray semicolon in my fileProcessing method that caused an infinite loop. Thank you all for your help.
while (lineMedals < 4);
Above line has a semicolon at the end. It is an infinite loop.
after file creation ,you use this below method
File medalsOutput = new File (outputTxt);
medalsOutput.createNewFile()
in ur code file not got created and exiting via syste.exit(1)