I made a java program that accepts a user input, but when running it in JGrasp after finishing the compile it just says "operation complete" and doesn't let me input anything or display any print text that I added in the code.
/*
* The file name of your program, Assign_1.java
*
* TCSS 143 – January 10th, 2015
* Assignment 1
*/
import java.util.Scanner;
/**
* This program allows 5 town populations to be entered then converted
* to stars based on each 1000.
*
* #author Thejai Riem
* #version 1/10/15
*/
public class Assign_1 {
/**
* For town1-5 variable for population # that changes later
*/
public static int town1;
public static int town2;
public static int town3;
public static int town4;
public static int town5;
public static void main(String[] theArgs) {
}
/**
* Gets population from user input of the 5 towns.
*
* #param theArgs is used for user input to scanner
*/
public static void getPopulation(String[] theArgs) {
Scanner population = new Scanner(System.in); // Keyboard input
System.out.println("Enter the population of town 1: ");
town1 = population.nextInt(); // Asks input for town population
System.out.println("Enter the population of town 2: ");
town2 = population.nextInt(); // Changes town(#) to user input
System.out.println("Enter the population of town 3: ");
town3 = population.nextInt();
System.out.println("Enter the population of town 4: ");
town4 = population.nextInt();
System.out.println("Enter the population of town 5: ");
town5 = population.nextInt();
}
/**
* Draws population one * for 1000 people
*
* #param theArgs is used for string output
*/
public static void drawPopulationBar(String[] theArgs) {
System.out.println();
System.out.println("POPULATION GRAPH:");
System.out.println("Town 1: " + town1 / 1000);
System.out.println("Town 2: " + town2 / 1000);
System.out.println("Town 3: " + town3 / 1000);
System.out.println("Town 4: " + town4 / 1000);
System.out.println("Town 5: " + town5 / 1000);
}
}
The reason it doesn't ask for input is that you're never routing to that section of the code. Note that all Java applications run by calling a main method. Notice that yours is empty. I think what you want is probably something like this:
import java.util.Scanner;
public class Assign_1 {
/**
* For town1-5 variable for population # that changes later
*/
public static int town1;
public static int town2;
public static int town3;
public static int town4;
public static int town5;
public static void main(String[] theArgs) {
getPopulation(theArgs);
drawPopulationBar(theArgs);
}
/**
* Gets population from user input of the 5 towns.
*
* #param theArgs is used for user input to scanner
*/
public static void getPopulation(String[] theArgs) {
Scanner population = new Scanner(System.in); // Keyboard input
System.out.println("Enter the population of town 1: ");
town1 = population.nextInt(); // Asks input for town population
System.out.println("Enter the population of town 2: ");
town2 = population.nextInt(); // Changes town(#) to user input
System.out.println("Enter the population of town 3: ");
town3 = population.nextInt();
System.out.println("Enter the population of town 4: ");
town4 = population.nextInt();
System.out.println("Enter the population of town 5: ");
town5 = population.nextInt();
}
/**
* Draws population one * for 1000 people
*
* #param theArgs is used for string output
*/
public static void drawPopulationBar(String[] theArgs) {
System.out.println();
System.out.println("POPULATION GRAPH:");
System.out.println("Town 1: " + town1 / 1000);
System.out.println("Town 2: " + town2 / 1000);
System.out.println("Town 3: " + town3 / 1000);
System.out.println("Town 4: " + town4 / 1000);
System.out.println("Town 5: " + town5 / 1000);
}
}
I also see that you're not actually using any of the command line arguments (any command line arguments get populated into the string array parameter in the main method invocation). So, you can probably remove those parameters from your other two methods (but you MUST leave it in the main method even if it's not being used since it is part of the signature that java expects).
I think that it's because you didn't fill out the main method of the program.
Related
I created a mortgage calculator which works just fine but I don't want to use println() when asking for user input. I want the user to be able to type on the same line; however, everytime i use print() the user input is taken but the print statements do not get read into the output until the very end.
Example of Current Output
2000
4.12
10
Principal: Annual Interest Rate: Period (years): Mortgage: $20.36
Current Code
package demos1;
import java.text.NumberFormat;
import java.util.Scanner;
/**
*
* #author nicka
*/
public class MortgageCalculator {
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
final byte MONTHS = 12;
final byte PERCENTAGE = 100;
Scanner scanner = new Scanner(System.in);
System.out.print("Principal: ");
double principal = scanner.nextDouble();
System.out.print("Annual Interest Rate: ");
double annInterest = scanner.nextDouble();
System.out.print("Period (years): ");
double periodY = scanner.nextDouble();
double monInterest = (annInterest/MONTHS)/PERCENTAGE;
double periodM = periodY*MONTHS;
double n = Math.pow((1 + monInterest) ,periodM);
double mortgage = principal*((monInterest*n)/(n-1));
String formatMortgage = NumberFormat.getCurrencyInstance().format(mortgage);
System.out.println("Mortgage: " + formatMortgage);
}
}
I was using println() before and the problem didn't occur. I also tried moving some stuff around but still the same issue..
I am in a Java class and I have a sales program as a project. My code will run but will not accept a second user's name as necessary in the code. It then makes a comparison between the two salaries. But my second calculation is not working correctly. Here is what I have:
package sales2;
import java.util.Scanner;
public class Sales2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Initialise scanner
String[] empName;
empName = new String[2];
double[] annualSales;
annualSales = new double[2];
System.out.printf("Please enter the employees name:"); // Question and input
empName[0] = input.nextLine();
System.out.printf("Please enter your annual sales:");
annualSales[0] = Double.parseDouble(input.nextLine());
double salary1 = Utils2.calculateSalary(annualSales[0]); // Read sales from input & calculate salary
System.out.println(empName[0] + "'s total yearly salary is: " + Utils2.numFormat(salary1)); // Print information for user
input.nextLine();
System.out.printf("Please enter the employees name:");
empName[1] = input.nextLine();
System.out.printf("Please enter your annual sales:");
annualSales[0] = Double.parseDouble(input.nextLine());
double salary2 = Utils2.calculateSalary(annualSales[1]); // Read sales from input & calculate salary
System.out.println(empName[1] + "'s total yearly salary is: " + Utils2.numFormat(salary2)); // Print information for user
if (salary1 > salary2){
System.out.println(empName[0] + " has a higher total annual compensation.");
System.out.println(empName[1] + " will need to increase their sales to match or exceed "
+ empName[0] + ", here is how much :" + (salary1 - salary2) );
}else if (salary1 < salary2){
System.out.println(empName[1] + " has a higher total annual compensation.");
System.out.println(empName[0] + " will need to increase their sales to match or exceed "
+ empName[1] + ", here is how much :" + (salary2 - salary1) );
}else {
System.out.println("\nBoth Salespersons have equal total annual compensation.");
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sales2;
/**
*
* #author etw11
*/
import java.text.DecimalFormat;
public class Utils2 {
public final static double FIXED_SALARY = 30000;
/**
* #param dec
* #return
*/
public static String numFormat(double dec) {
return new DecimalFormat("##,##0.00").format(dec);
}
/**
* Calculates the salary based on the given sales.
* #param sales The annual sales
* #return The calculated salary.
*/
public static double calculateSalary(double sales) {
double commissionRate = 0.10d;
if (sales < 320000) {
commissionRate = 0.00d;
} else if (sales >= 320000 && sales < 400000) {
commissionRate = 0.08d;
}
// System.out.println("The current commission is " + (int)
(commissionRate * 100) + "% of total sales.");
return FIXED_SALARY + (sales * commissionRate);
}
}
change this:
double annualSales = input.nextDouble();
to this:
double annualSales = Double.parseDouble(input.nextLine());
Found my issue. In this line:
annualSales[0] = Double.parseDouble(input.nextLine());
It should be:
annualSales[1] = Double.parseDouble(input.nextLine());
Hey guys I have been working on this program for class the past couple hours and just cant seem to get these last 2 issues resolved. Its basically a slightly modified CashRegister class with basic functions through a menu. The problems I am having are:
1) After the user makes a menu selection for the first time, every subsequent time the menu shows up in console twice and I cant seem to find a fix for this.
2) Also whenever I choose to display the content of my CashRegister, the first line is always output as 0.00 no matter the input.
Here is my CashRegister class followed by my tester:
import java.util.ArrayList;
/**
*
*/
/**
* #author Cole
*
*/
public class CashRegister {
private double dailyTotal;
private double totalPrice;
ArrayList<Double> items;
/**
Constructs a cash register with cleared item count and total.
*/
public CashRegister()
{
items = new ArrayList<Double>();
dailyTotal = 0;
totalPrice= 0;
}
/**
Adds an item to this cash register.
#param price the price of this item
*/
public void addItem(double price)
{
items.add(price);
dailyTotal = dailyTotal + price;
}
/**
Gets the price of all items in the current sale.
#return the total amount
*/
public double getTotal()
{
for(int x=0; x<items.size(); x++){
totalPrice = totalPrice + items.get(x);
}
return totalPrice;
}
/**
Gets the number of items in the current sale.
#return the item count
*/
public int getCount()
{
return items.size();
}
/**
Clears the item count and the total.
*/
public void clear()
{
items.clear();
totalPrice = 0;
}
public void display(){
for(int x=0; x<items.size(); x++){
System.out.printf("%10.2f%n", items.get(x));
}
System.out.println("------------------------------");
}
public double getDailyTotal(){
dailyTotal = dailyTotal + totalPrice;
return dailyTotal;
}
}
import java.util.ArrayList;
import java.util.Scanner;
/**
*
*/
/**
* #author Cole
*
*/
public class Prog2 {
/**
* #param args
*/
public static final String MENU = "******************************************\n" +
"* Enter \"n\" to start a new Cash Register. *\n" +
"* Enter \"a\" to add an item to the current Cash Register. *\n" +
"* Enter \"d\" to display the total of the current Cash Register. *\n" +
"* Enter \"e\" to exit the program. *\n" +
"******************************************";
public static final String NEW_CUSTOMER = "n";
public static final String ADD_ITEM = "a";
public static final String DISPLAY = "d";
public static final String EXIT = "e";
public static void main(String[] args) {
// TODO Auto-generated method stub
CashRegister register = new CashRegister();
Scanner keyboard = new Scanner(System.in);
String input;
double userInput = 0;
do {
input = printMenu(keyboard);
if(input.equals(NEW_CUSTOMER)){
register.getDailyTotal();
register.clear();
}
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
register.addItem(userInput);
userInput = keyboard.nextDouble();
}
else if(input.equalsIgnoreCase(DISPLAY)){
register.display();
System.out.println("Total: " + register.getTotal());
System.out.println("Item Count: " +register.getCount());
}
else if(input.equalsIgnoreCase(EXIT)){
System.out.printf("Daily Sales Total: " + "%.2f%n",register.getDailyTotal());
System.out.println("Program Ended...");
break;
}
}while(input != EXIT);
}
public static String printMenu(Scanner input){ //this method displays the menu for the user
String response = "no reponse yet";
System.out.println(MENU);
response = input.nextLine();
return response; //response returned based on the users input
}
}
You need to get input from the user before you add the item, that's why you are getting a 0 for your first item. Since your value for userInput is set to 0 at the beginning and your statements are switched you will always initialy create an item with 0.0 for it's value and all the other values will be one step behind the actual inputs.
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
userInput = keyboard.nextDouble();
register.addItem(userInput);
}
Okay, the objective of this program is to input String values, such as penny, dime, quarter, and nickel, into the ArrayList purse in class Purse. Then once Purse is executed through the PurseMain class then the Coin class is supposed to take the string values of the coin names that were added into the ArrayList purse and add their dollar values together. My professor told us to create the coin values in a third Class called Coin and to create another ArrayList in PurseMain. But really my main question is, how do you call the objects that were created in the Coin Class into the ArrayList in PurseMain? Any help would be appreciated. Thanks.
package purse;
import java.util.Scanner;
import java.util.ArrayList;
/**
* The Purse program creates an ArrayList called purse that gets printed out,
reversed, and transfered into another ArrayList called purse2.
*
* - ArrayList purse
* - ArrayList purse2
* - Scanner coin - the Scanner that is used to type the contents of ArrayList purse
* - Scanner coin2- the Scanner that is used to type the contents of ArrayList purse2
* - String input - contains Scanner coin and is used to fill ArrayList purse
* - String input2- contains Scanner coin2 and is used to fill ArrayList purse2
* - String end - sentinel for ending the process inputting strings into Scanner coin and Scanner coin2
*
*/
public class Purse
{
ArrayList<String> purse = new ArrayList<>();
/**
* fills ArrayList purse and purse2 with U.S coin names
* purse gets printed out and then again is printed in reverse
* purse2 is printed
*/
public void addCoin()
{
String penny = "penny";
String nickel = "nickel";
String dime = "dime";
String quarter = "quarter";
String end = "done";
Scanner coin = new Scanner (System.in);
String input = " ";
System.out.println("Please put as many coins of U.S currency as you like into the purse, hit the ENTER button after each coin and, type 'done' when finished: ");
while (!input.equalsIgnoreCase ("done"))
{ input = ( coin.nextLine());
if (input.equalsIgnoreCase("penny")||input.equalsIgnoreCase("nickel")||input.equals IgnoreCase("dime")||input.equalsIgnoreCase("quarter")||input.equalsIgnoreCase(en d))
{
purse.add(input);
purse.remove(end);
}
else{
System.out.println("Please input a coin of U.S currency.");
}
}
}
/**
#return ArrayList purse
*/
public ArrayList<String> printPurseContents()
{
System.out.println("Contents of the purse: " + purse);
return purse;
}
/** checks whether purse2 has the same coins in the same order as purse
* #return
* #param purse2
*/
public boolean sameContents(Purse purse2)
{
if (purse2.purse.equals(purse))
{
return true;
}
else
{
return false;
}
}
/**
* checks whether purse2 has the same coins as in purse, disregarding the order
* #param purse2
* #return
*/
public boolean sameCoins(Purse purse2)
{
if( purse2.purse.containsAll(purse))
{
return true;
}
else
{
return false;
}
}
/**
* adds contents of purse into purse2 and clears purse of its contents
* #param purse2
*/
public void transfer(Purse purse2)
{
purse2.purse.addAll(purse);
purse.clear();
System.out.println("The second purse now has: " + purse2.purse );
System.out.println("and the first purse has: " + purse);
}
}
----------PurseMain
package purse;
import java.util.ArrayList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**legalcoin = new ArrayList<Coin>; <-----
* legalcoin.add( new Coin ("Penny", .01); <--- Professor said to do
*
* #author
* 9/01/2015
* Lab I
*/
public class PurseMain
{
private ArrayList<Coin> legalCoin = new ArrayList<>();
legalCoin.add (new Coin ("Penny",0.01));
public static void main(String[] args)
{
Purse purse1 = new Purse();
purse1.addCoin();
purse1.printPurseContents();
Purse purse2 = new Purse();
purse2.addCoin();
purse2.printPurseContents();
System.out.println("Both of the purses have the same contents and the contents is in the same order: " + purse2.sameContents(purse1));
System.out.println("Both of the purses have the same contents: " +purse2.sameCoins(purse1));
}
}
----------Coin
package purse;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/** private string name;
* private double value;
* sum up value method
*
* #author
*/
public class Coin
{
private String Penny = "penny";
private String Nickel = "nickel";
private String Dime = "dime";
private String Quarter = "quarter";
private double penny = 0.01;
private double nickel = 0.05;
private double dime = 0.10;
private double quarter = 0.25;
public void SumUpValue()
{
}
}
You will need to have a new Coin pouch in your purse(requirement wise). So, have a coin pouch that takes list of coins in it. Since the purse has the coin pouch, it would be a property of your purse.
public class Coin{
private String type;
private String currencyType;
//more fields and getters and setters
}
public class Purse{
ArrayList<String> purse = new ArrayList<>();
List<Coins> coinPouch = new ArrayList<>();//contains coin objects
.
.
.
.
private void addCoins(String coinType){
Coin coin = new Coin();
coin.setType(coinType);
coinPouch.add(coin);
}
}
Your modified code for adding coins would be like:
if (input.equalsIgnoreCase("penny")|| input.equalsIgnoreCase("nickel") ||input.equalsIgnoreCase("dime")||input.equalsIgnoreCase("quarter")||input.equalsIgnoreCase(end)){
addCoins(input);//Adds coins to the list of coins objects and the purse now has the coin pouch :D
purse.remove(end);
}
else{
System.out.println("Please input a coin of U.S currency.");
}
I'm creating a small 'game' program where a player enters a floor/room number, but when the player guess it gets stuck and loops on a single player and doesn't move to the next player and doesn't tell if the player is correct or incorrect as a guess where the dog is being held in the building.
PuppyPlay.java:
import java.util.Random;
import java.util.Scanner;
/**
* This program is used as a driver program to play the game from the
* class LostPuppy.
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
*/
public class PuppyPlay{
/**
* Driver program to play LostPuppy.
*
* #param theArgs may contain file names in an array of type String
*/
public static void main(String[] theArgs){
Scanner s = new Scanner(System.in);
LostPuppy game;
int totalFloors;
int totalRooms;
int floor;
int room;
char[] players = {'1', '2'};
int playerIndex;
boolean found = false;
Random rand = new Random();
do {
System.out.print("To find the puppy, we need to know:\n"
+ "\tHow many floors are in the building\n"
+ "\tHow many rooms are on the floors\n\n"
+ " Please enter the number of floors: ");
totalFloors = s.nextInt();
System.out.print("Please enter the number of rooms on the floors: ");
totalRooms = s.nextInt();
s.nextLine(); // Consume previous newline character
// Start the game: Create a LostPuppy object:
game = new LostPuppy(totalFloors, totalRooms);
// Pick starting player
playerIndex = rand.nextInt(2);
System.out.println("\nFloor and room numbers start at zero '0'");
do {
do {
System.out.println("\nPlayer " + players[playerIndex]
+ ", enter floor and room to search separated by a space: ");
floor = s.nextInt();
room = s.nextInt();
//for testing, use random generation of floor and room
//floor = rand.nextInt(totalFloors);
//room = rand.nextInt(totalRooms);
} while (!game.indicesOK(floor, room)
|| game.roomSearchedAlready(floor, room));
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
} while (!found);
playerIndex = (playerIndex + 1) % 2;
System.out.println("Great job player " + players[playerIndex] +"!");
System.out.println("Would you like to find another puppy [Y/N]? ");
} while (s.nextLine().equalsIgnoreCase("Y"));
}
}
LostPuppy.java:
import java.util.Random; // Randomize the dog placement in building
import java.util.Scanner; // User input
/**
* This program is used as a program to play the game from the
* driver PuppyPlay.java
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
*/
public class LostPuppy{
private char[][] myHidingPlaces; // Defining class fields for assignment
private int myFloorLocation;
private int myRoomLocation;
private char myWinner;
private boolean myFound;
/**
* Creates constructor takes floor/room numbers inputted by user
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public LostPuppy(int theFloors, int theRooms) {
Random random = new Random();
myHidingPlaces = new char[theFloors][theRooms];
// Filling array with spaces
int i;
for (i = 0; i < theFloors; i++) {
for (int k = 0; k < theRooms; k++) {
myHidingPlaces[i][k] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
/**
* Checks if room has been searched prior
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean roomSearchedAlready(int theFloors, int theRooms) {
boolean searchedRoom;
if (myHidingPlaces[theFloors][theRooms] == ' ') {
myHidingPlaces[theFloors][theRooms] = 'S';
searchedRoom = false;
} else {
searchedRoom = true;
}
return searchedRoom;
}
/**
* Checks if the puppy has been found
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean puppyLocation(int theFloors, int theRooms) {
if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
myFound = true;
} else {
myFound = false;
}
return myFound;
}
/**
* Checks if floors and rooms won't throw out of bounds error
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean indicesOK(int theFloors, int theRooms) {
boolean indicesFit;
if (theFloors < numberOfFloors() && theRooms < numberOfRooms()) {
indicesFit = true;
} else {
indicesFit = false;
}
return indicesFit;
}
/*
* Checks # of floors and returns it
*/
public int numberOfFloors() {
return myHidingPlaces.length;
}
/*
* Checks # of rooms and returns it
*/
public int numberOfRooms() {
return myHidingPlaces[0].length;
}
/**
* Checks which player found the dog and won, or if not checks to see what player
* guessed wrong and puts their # in the box
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
* #param thePlayer for 1st or 2nd player
*/
public boolean searchRoom(int theFloors, int theRooms, char thePlayer) {
if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
myFound = true;
myWinner = thePlayer;
} else {
myHidingPlaces[theFloors][theRooms] = thePlayer;
myFound = false;
}
return myFound;
}
/*
* toString displays the current hidingPlaces array and it’s contents EXCEPT
* the location of the puppy which remains hidden until he/she is found at
* which point toString will be called (by the driver) and both the player
* who found the puppy and a ‘P’ will be displayed in the same cell….
*
*
*
*/
public String toString() {
return null;
}
}
To run this code you'll need to put both codes with their respective posted names and run PuppyPlay.java with LostPuppy.java in the same folder FYI.
The problem lied in this place in PuppyPlay:
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
So your program expect you to input something here, and it will keep waiting until you press enter, so you can just remove that line: s.nextLine();