So, currently my voting system works well but now I'm getting a divide by zero code :/. This shouldn't be happening because the "Total integer always has a numerical value greater than zero (unless I'm missing Something?). Anyways I want the program to take votes and organize them as female and male voters and whether they voted for Trump or Clinton.
package vote;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class vote {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Declare Strings and Initialize
String PCandidate1=null;
String Gender1=null;
String Economy1= null;
//Declare Integer
int Age;
int Trump=0;
int Clinton=0;
int Male=0;
int Female=0;
int MaleT=0;
int FemaleT=0;
int MaleC=0;
int FemaleC=0;
int Young=0;
//all data read from a dialog box comes into a string
String svalue,output ="";
//Need to Implement While loop to keep collecting data
int counter=0;
while(counter<4) {
counter++;
//Vote for Presidential Candidate and Tally the Votes!
svalue =JOptionPane.showInputDialog(null,"Will you Vote for Clinton or Trump?","Input Data", JOptionPane.QUESTION_MESSAGE);
svalue=JOptionPane.showInputDialog(null,"Are you Male or Female (M/F)?","Input Data", JOptionPane.QUESTION_MESSAGE);
if (svalue.equals("trump")||(svalue.equals("Trump")))
{
if (svalue.equals("F")||(svalue.equals("f")))
Trump++;
Female++;
FemaleT++;}
if (svalue.equals("Trump")||(svalue.equals("trump")))
{
if (svalue.equals("M")||(svalue.equals("m")))
MaleT++;
Trump++;
Male++;}
if (svalue.equals("clinton")||(svalue.equals("Clinton"))){
if (svalue.equals("M")||(svalue.equals("m")))
Clinton++;
MaleC++;
Male++;}
if (svalue.equals("Clinton")||(svalue.equals("clinton"))){
if(svalue.equals("F")||(svalue.equals("f")))
FemaleC++;
Clinton++;
Female++;}
PCandidate1= (svalue);
//Inpute Users Age
svalue=JOptionPane.showInputDialog(null,"What is Your Age?","Input Data", JOptionPane.QUESTION_MESSAGE);
Age=Integer.parseInt(svalue);
if (Age<=25)
Young++;
// Get Users Input about State of the Economoy
svalue=JOptionPane.showInputDialog(null,"Do you feel the economy is getting better?","Input Data", JOptionPane.QUESTION_MESSAGE);
Economy1= (svalue);
}
int Total=Male+Female;
//Output The Data to Form
output=output+"Users Voted For Trump: " + Trump +"\n"
+ "Users Voted For Clinton: " + Clinton+ "\n"
+"Total Users Polled: " +(Total)+"\n"
+ "Male Voters: " + Male+ "\n"
+ "Female Voters: " + Female+ "\n"
+ "% Female Voters for Clinton: " + (FemaleC/Clinton)*100+ "\n"
+ "% Male Voters for Clinton: " + (MaleC/Clinton)*100+ "\n"
+ "% Female Voters for Trump: " + (FemaleT/Total)*100+ "\n"
+ "% Male Voters for Trump: " + (MaleT/Total)*100+ "\n"
+ "Number of Young People Polled: " + Young+ "\n"
;
//write all in a dialog box
JOptionPane.showMessageDialog(null,
output,"Output:",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
You have a lot of problems with your if-statements:
if (svalue.equals("clinton")||(svalue.equals("Clinton"))){
if (svalue.equals("M")||(svalue.equals("m")))
Clinton++;
MaleC++;
Male++;}
You don't have brackets in your second if statement.
Your if's check whether a value is equal to both "Clinton", and "m". This means that your second if-statement will never be entered. So Clinton will never be updated and will always be zero. (And we thought it was the Russians..)
You need to have a second variable for whether the voter is male or female and check this in your second if-statement instead of overriding svalue
Side note: proper indenting will help you spot these errors
So something more like this:
gender =JOptionPane.showInputDialog(null,"Are you Male or Female (M/F)?","Input Data", JOptionPane.QUESTION_MESSAGE);
//…
if (svalue.equals("clinton")||(svalue.equals("Clinton"))){
if (gender.equals("M")||(gender.equals("m"))) {
Clinton++;
MaleC++;
Male++;
}
//Etc
Related
So I have been struggling with this prompt for some time. Basically I need to use dialog boxes in the creation of a program to be used in billing for construction companies. The prompt is as follows. First: Read the following data from separate dialog boxes. This needs to be done for the name of the construction firm, name of the customer, number of labor hours for the foreman, number of workers, number of days on the job, and finally the cost of materials. Second: the following must be calculated from the information obtained from the dialog boxes. The calculations are as follows: Foreman labor cost=foreman labor hours times 60, worker labor cost= number of days times 8 hours per day times number of workers times $30, job fee= Forman labor cost+ worker labor cost+ materials, discount= job fee times 10%, the final amount due= job fee- discount. Lastly, all the data must be printed. The output should look something like Construction firm name, customer:xxxxx, number of days =xxxxx, foreman labor cost =xxxxx, worker labor cost =xxxxx, Materials cost =xxxxx, Job Fee =xxxxx, Discount=xxxxx, Final Amount Due =xxxxx. My question is I cannot get the code to run to produce the output I need using the information from dialog boxes? Every time I try and run the program it is terminated so I am a bit confused I am fairly new to Java so any help would be appreciated The code I have so far is as follows:
package bill;
import javax.swing.JOptionPane;
public class ContractorBill
{
public static void main(String[]args) {
}
double forhours,workers,daysonjob,costofmaterials,flcost,wlcost,jobfee,discount,finalamount;
String fname,cname,forstring,wstring,dojstring,comstring,printdata="";{
fname=JOptionPane.showInputDialog(null,"Enter the name of the construction firm","Input Data",JOptionPane.QUESTION_MESSAGE);
cname=JOptionPane.showInputDialog(null,"Enter the customer's name","Input Data",JOptionPane.QUESTION_MESSAGE);
forstring=JOptionPane.showInputDialog(null,"Enter the number of labor hours required for the foreman","Input",JOptionPane.QUESTION_MESSAGE);
wstring=JOptionPane.showInputDialog(null, "Enter the number of workers required","Input",JOptionPane.QUESTION_MESSAGE);
dojstring=JOptionPane.showInputDialog(null,"Enter the number of days required to complete the job","Input",JOptionPane.QUESTION_MESSAGE);
comstring=JOptionPane.showInputDialog(null,"Enter the cost of materials required for the job"+"Input",JOptionPane.QUESTION_MESSAGE);
forhours=Double.parseDouble(forstring);
workers=Double.parseDouble(wstring);
daysonjob=Double.parseDouble(dojstring);
costofmaterials=Double.parseDouble(comstring);
flcost=60*(forhours);
wlcost=8*(daysonjob)+30*(workers);
jobfee=(flcost)+(wlcost)+(costofmaterials);
discount=(jobfee)*0.10;
finalamount=(jobfee)-(discount);
printdata=printdata+"CONSTRUCTION FIRM NAME="+fname+"\n"+
"CUSTOMER:"+cname+"\n"+
"Number of days ="+daysonjob+"\n"+
"Forman labor cost ="+flcost+"\n"+
"Worker Labor Cost ="+wlcost+"\n"+
"Materials cost ="+costofmaterials+"\n"+
"Job Fee ="+jobfee+"\n"+
"Discount ="+discount+"\n"+
"Final Amount Due ="+finalamount+"\n";
JOptionPane.showMessageDialog(null,printdata,"Output:",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}}
The main method is the only one called automatically, and it contains no statements that would cause it not to terminate immediately.
See this altered version, and carefully read the code comments:
import javax.swing.JOptionPane;
public class ContractorBill {
double forhours, workers, daysonjob, costofmaterials, flcost, wlcost, jobfee, discount, finalamount;
String fname, cname, forstring, wstring, dojstring, comstring, printdata = "";
public static void main(String[] args) {
new ContractorBill(); // call the (newly added) constructor
}
// this has now been turned from a code block into a constructor
ContractorBill() {
fname = JOptionPane.showInputDialog(null, "Enter the name of the construction firm", "Input Data", JOptionPane.QUESTION_MESSAGE);
cname = JOptionPane.showInputDialog(null, "Enter the customer's name", "Input Data", JOptionPane.QUESTION_MESSAGE);
forstring = JOptionPane.showInputDialog(null, "Enter the number of labor hours required for the foreman", "Input", JOptionPane.QUESTION_MESSAGE);
wstring = JOptionPane.showInputDialog(null, "Enter the number of workers required", "Input", JOptionPane.QUESTION_MESSAGE);
dojstring = JOptionPane.showInputDialog(null, "Enter the number of days required to complete the job", "Input", JOptionPane.QUESTION_MESSAGE);
comstring = JOptionPane.showInputDialog(null, "Enter the cost of materials required for the job" + "Input", JOptionPane.QUESTION_MESSAGE);
forhours = Double.parseDouble(forstring);
workers = Double.parseDouble(wstring);
daysonjob = Double.parseDouble(dojstring);
costofmaterials = Double.parseDouble(comstring);
flcost = 60 * (forhours);
wlcost = 8 * (daysonjob) + 30 * (workers);
jobfee = (flcost) + (wlcost) + (costofmaterials);
discount = (jobfee) * 0.10;
finalamount = (jobfee) - (discount);
printdata = printdata + "CONSTRUCTION FIRM NAME=" + fname + "\n"
+ "CUSTOMER:" + cname + "\n"
+ "Number of days =" + daysonjob + "\n"
+ "Forman labor cost =" + flcost + "\n"
+ "Worker Labor Cost =" + wlcost + "\n"
+ "Materials cost =" + costofmaterials + "\n"
+ "Job Fee =" + jobfee + "\n"
+ "Discount =" + discount + "\n"
+ "Final Amount Due =" + finalamount + "\n";
JOptionPane.showMessageDialog(null, printdata, "Output:", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
I want to pun a condition in an multidimesional array and I'm stuck. My method should return a name in a specific format. If find a title like (Mr.,Mrs) return Title , first letter from name , and the full surname. If title is not found return full name + full surname. Eg. Ms. S. T. Mark or Smith T. Rose or Tony Mark.
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. ","Miss"},
{"Smith ", "Jones "},
{"Tony ", "Jhon "},
{"Mark ","Rose "}
};
if (names[0].equals(names)&& names[1].equals(names)&&names[2].equals(names)&& names[3].equals(names)){
return names[0][0] + names[1][0].substring(0,1)+". " + names[2][0].substring(0,1)+". "+names[3][0];}
return"";
As I wrote in the comment this doesn't make sense:
names[0].equals(names)
names[0] is string array (String[]) containing: {"Mr. ", "Mrs. ", "Ms. ","Miss"}
While names is array of string arrays (String[][]) containing everything, so you can't compare them in such way, it will always be false.
Moreover you actually shouldn't ever use equals for arrays. Please check this post for more information:
https://stackoverflow.com/a/8777266/7624937
Now, as suggested by #Tschallacka you should probably create Person class, e.g:
class Person {
String title;
String name;
String surname;
}
and then implement functions which are of your interest. So according to your description such function would look like this:
public String introduceYourself() {
if (title != null) {
return title + " " + name.charAt(0) + " " + surname;
} else {
return name + " " + surname;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String grade = JOptionPane.showInputDialog(null, "Please Specify Your Grade");
String First_name = JOptionPane.showInputDialog(null, "What is your First Name?");
String Last_name = JOptionPane.showInputDialog(null, "What is your Last Name?");
]JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
}
How do I get the part where it says "Your Last Name is " + Last_Name to print the correct string? in my code it says that the string cannot be converted to an integer but the rest of that line works fine (using Netbeans IDE)
You are trying to pass multiple messages as separate parameters to the method JOptionPane.showMessageDialog, however the method only accepts a single message parameter. However, this parameter is not limited to just Strings; you can actually pass any Object as the message. See the JOptionPane javadocs for details on how JOptionPane handles various types of message parameters.
I think there are a couple approaches that could be used. One approach is to create a String that concatenates all of the results together. My suggestion would be to use a newline character (\n) to concatenate the results, so they appear one per line. Here is an example:
String message = "You are a " + grade + "\n"
+ "Your Name is " + First_name + "\n"
+ "Your Last Name is " + Last_name;
JOptionPane.showMessageDialog (null, message);
Another approach is to create an array out of the results, and pass the array as the message parameter:
String[] message = {
"You are a " + grade,
"Your Name is " + First_name,
"Your Last Name is " + Last_name
};
JOptionPane.showMessageDialog (null, message);
works also in the constructor :
JOptionPane.showMessageDialog(null, "You are a " + grade+ "\nYour Name is " + First_name+
"\nYour Last Name is " + Last_name);
and probably delete ] in your last line of code
JOptionPane has 3 showMessageDialog() methods, each with different arguments, let's look at each of them, but first we're going to use the following String:
String message = "You are a " + grade + " Your Name is " + First_name " Your Last Name is " + Last_name;
showMessageDialog(Component parentComponent, Object message) this method recieves the parentComponent (it shouldn't be null, instead pass the reference to your JFrame because otherwise you won't be blocking the parent component, so it won't be a modal Dialog) and the message, in your case it would be the String containing the name, last name, etc, you could use it this way:
JOptionPane.showMessageDialog(frame, message);
showMessageDialog(Component parentComponent, Object message, String title, int messageType) this method allows you to modify the icon (or the message type (A list of the full message types can be found on the docs) and the title of the dialog and you can use it as:
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) this allows you to use a custom icon and you can use it this way:
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
For more information you can check How to use Dialogs
Now, if you want to improve the format you can either use html tags as:
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
Or create your own custom JPanel where you add your components to it and then add that JPanel to the showMessageDialog on the Object message argument, but I'm leaving that part to you
This code will create the above output images, however you need to change the image path to your own path, the custom icon has been taken from here
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class DialogExamples {
private JFrame frame;
private ImageIcon icon = new ImageIcon("/home/jesus/Pictures/L5DGx.png");
public static void main (String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DialogExamples().createAndShowGui();
}
});
}
public DialogExamples() {
System.out.println(icon);
}
public void createAndShowGui() {
frame = new JFrame("Example");
String name = "Your name is Frakcool";
String grade = "Your grade is 5";
String lastname = "Your lastname is YajiSuzu";
String message = "<html>" + name + "<br/>" + lastname + "<br/>" + grade + "</html>";
// String message = name + " " + lastname + " " + grade;
JOptionPane.showMessageDialog(frame, message);
JOptionPane.showMessageDialog(frame, message, "My title", JOptionPane.QUESTION_MESSAGE);
JOptionPane.showMessageDialog(frame, message, "My title2", JOptionPane.ERROR_MESSAGE, icon);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
In your case you're getting the exception:
String cannot be converted to an int
because you're sending 4 parameters here:
JOptionPane.showMessageDialog (null,"You are a " + grade, "Your Name is " + First_name, "Your Last Name is " + Last_name);
In this case, you're using the 2nd method I showed you above, so it's expecting to receive an int messageType on the 4th parameter, not a String.
This isn't something as a console.log() in JS, here you concatenate Strings with + operator, not with a , (comma).
NOTE:
As an aside note, your variable and method names should start with lowerCamelCase while your classes should start with UpperDromedaryCase as stated on the Java naming conventions
NOTE2:
You're not placing your program on the EDT which could cause you problems in the future, so be careful, my above code already solved that problem
Count keeps coming up zero. I'm just trying to read the text file and look for the word, and display the count back to the user.
I'm not sure where it's falling apart. The If statement I think, but not sure where the syntax is going wrong. Thanks for any help!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class TextSearchFromFile
{
public static void main(String[] args) throws FileNotFoundException
{
boolean run = true;
int count = 0;
//greet user
JOptionPane.showMessageDialog(null,
"Hello, today you will be searching through a text file on the harddrive. \n"
+ "The Text File is a 300 page fantasy manuscript written by: Adam\n"
+ "This exercise was intended to have the user enter the file, but since \n"
+ "you, the user, don't know which file the text to search is that is a \n"
+ "bit difficult.\n\n"
+ "On the next window you will be prompted to enter a string of characters.\n"
+ "Feel free to enter that string and see if it is somewhere in 300 pages\n"
+ "and 102,133 words. Have fun.",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
while (run)
{
try
{
//open the file
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
//prompt user for word
CharSequence findWord = JOptionPane.showInputDialog(null,
"Enter the word to search for:",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
count = 0;
while (scanner.hasNext())
{
if ((scanner.next()).contains(findWord))
{
count++;
}
} //end search loop
//output results to user
JOptionPane.showMessageDialog(null,
"The results of your search are as follows: \n"
+ "Your String: " + findWord + "\n"
+ "Was found: " + count + " times.\n"
+ "Within the file: An Ever Throne Tale 1.txt",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
} //end try
catch (NullPointerException e)
{
JOptionPane.showMessageDialog(null,
"Thank you for using the Text Search.",
"Text Search",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} //end run loop
} // end main
} // end class
EDIT:
Need help again. The instructor changed the parameters of the project and now I need to find word fragments like "th" or "en" and count those as well.
This I feel is beyond what he has taught and I have no idea how to make that work. I've googled until I can't google anymore.
You have to provide a File Object to Scanner in order to read the file, currently everything is getting searched in a String "An Everthrone Tale 1.txt"
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
And for searching a word, you need to do like this:
while (scanner.hasNext())
{
if (findWord.equals(scanner.next()))
{
count++;
}
}
and if you want to perform case-insensitive search then use String#equalsIgnoreCase instead of String#equals
Hope this helps
package Homework;
import java.util.Scanner;
class FantasyGame{
public static void main ( String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest!");
System.out.println("Enter the name of your character: ");
String name;
name = scan.nextLine();
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest, " + (name) + "! " + "You will now assign attributes to your character, the total value assigned must not exceed 15 or be under 0, or the points will be assigned by default! (Type any NUMBER to continue)");
int ans = scan.nextInt();
System.out.println("Enter Strength (0-15): ");
int str = scan.nextInt();
System.out.println("Enter Health (0-15): ");
int hp = scan.nextInt();
System.out.println("Enter Luck (0-15): ");
int lck = scan.nextInt();
if (str + hp + lck <= 15)
{
System.out.println("Congratulations! You have successfully created your character!");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (str));
System.out.println("Health: " + (hp));
System.out.println("Luck: " + (lck));
}
if (str + hp + lck > 15)
{
System.out.println("You have give your character too many attribute points! Default values have been assigned.");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (5));
System.out.println("Health: " + (5));
System.out.println("Luck: " + (5));
}
}
}
I want to make a text-based game for my history class and I know basic Java enough to make a small one with just variables and stuff but I don't know how I can make it so that it runs directly as an applet with a black background and white text that shows up and responds to what you type, like the code above does in the console.
I've tried the command prompt method but all I get is "Access is Denied."
Also, when I try to export in eclipse, the launch configuration always goes to a class I don't want. Sorry but I am really confused and need a lot of help on this.
to write a simple applet, http://docs.oracle.com/javase/tutorial/deployment/applet/ this tutorial from oracle will walk you through it fairly well, it shouldn't be too hard to rearrange your code then
I figured it out. I just exported my program as a .jar and used Jar2Exe and it worked perfectly. Thanks!
You have not made you class public and that is why you are getting error "Access is denied" because it is not visible any more. Compiler is not able to find that class. Just write
....
//change is here
public class FantasyGame
{
....
}
....
Thanks !