Main Blog
Our most important blog

Home Page




Posts Tagged ‘Java Util’

Help Please! My casino program (java)?

My casino class won’t compile. When the user enters their name, I’m trying to make a new player object. I want to keep track of the player and allow them to play casino games. There may be something wrong with my class import statement. I’m not sure.

————————————————

import java.util.Scanner;

public class player{

private String name;
private double balance;
Scanner reader;

public player(){
name = “”;
balance = 0;
reader = new Scanner(System.in);
}

public player(String n){
name = n;
balance = 50;
reader = new Scanner(System.in);
}

public String getName(){
return name;
}

public double getBalance(){
return balance;
}

}

————————————–

import player.class
import java.util.Scanner;

public class casino{

public static void main(String[] args){

Scanner scanner = new Scanner(System.in);
System.out.println(”Good day. What’s your name.”);
new casino(scanner.nextLine());
System.out.println(getName() + “, What would like to do?”);
}

}

By: John



No Comments

Need help on a Java Assignment?

Its a BMI calculator. I’ve gotten most of it done, but i don’t know how to take out the first and second number of the height out separately so that I can convert them to inches and then to meters. Help?

*/
import java.util.Scanner;
public class BMI
//import the Scanner class //class declaration
{

public static void main(String [] args) //beginning of main method
{

Scanner in = new Scanner(System.in);
int userWeightLbB = 0;
int userWeightInB = 0;
double userWeightKg = 0;
int index = 0;
int second = 2;

System.out.print(”Enter your name (first last): ” );
String userName = in.next();
System.out.println();

System.out.print(”Enter your weight in pounds ( e.g. 175): “);
String userWeightLb = in.next();
userWeightLbB = Integer.parseInt(userWeightLb);
System.out.println();

System.out.print(”Enter your height in feet and inches ( e.g. 5 11): “);
String userHeightIn = in.next();

//converters
userWeightKg = userWeightLbB * 0.45358237;
userHeightIn = (feet * 12) + inches ;

}
}
I figured that in David, and now I’m getting a compiler error on
userHeightIn = (Feet * 12) + Inches ;

something like found int but expected string
it compiles fine but doesn’t do so well when you actually use it. please help

/**
* Write a description of class BMI here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.Scanner;
public class BMI
//import the Scanner class //class declaration
{

public static void main(String [] args) //beginning of main method
{

Scanner in = new Scanner(System.in);
int userWeightLbB = 0;
int userWeightInB = 0;
double userWeightKg = 0;
double userHeightInches = 0;
double userBMI = 0;
double userHeightMeters = 0;
int index = 0;
int second = 2;
String totalUserBMI = “”;

System.out.print(”Enter your name (first last): ” );
String userFirstName = in.next();
String userLastName = in.next();
System.out.println();

Sy

By: white.rabbit_y2k



1 Comment

Java Program - searching strings?

I am creating a program that allows the user to select a file on their computer, it then reads the file, switches all instances of ‘this’ with ‘that’, reverses the order of characters, and then display the number of charachters, number of times the #4 appears, and the new string.
for example: for input line “this4cats”, the output line should be “9,1,stac4tahT
I am stuck on how to get it so that I can use the file selected to be searched and reveresed. I have the following code and cant get past where I am.

import java.util.Scanner;
import javax.swing.JFileChooser;

public class StringChanger {

public static void main(String[] args) throws Exception{

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(null)
== JFileChooser.APPROVE_OPTION){
java.io.File file = fileChooser.getSelectedFile();

Scanner input = new Scanner(file);

while (input.hasNext()){
System.out.println(input.nextLine());

file.length();
System.out.println(file.length());
int count = 0;
for (int i = 0; i < file.length(); i++){
char c = file.charAt(i);
if (c=='4'){
count++;

}
}
System.out.println(count);

}

}
}

}
import java.util.Scanner;
import javax.swing.JFileChooser;

public class Project4 {

public static void main(String[] args) throws Exception{

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(null)
== JFileChooser.APPROVE_OPTION){
java.io.File file = fileChooser.getSelectedFile();

Scanner input = new Scanner(file);

while (input.hasNext()){
System.out.println(input.nextLine());

file.length();
System.out.println(file.length());

int[] count = countNumbers(file.);

for (int i= 0; i < count.length; i++){
if (count[i] !=0)
System.out.println((char)('4' + i) + " appears " +
count[i] + ((count[i] == 1) ? " time" : " times"));
}
}
}
}

public static int[] countNumbers(String file){
int [] count = new int[20];

for (int i = 0; i < file.length(); i++){
if (Character.isLetter(file.charAt(i)))
count[file.charAt(i) - '4']++;

}return count;

}
}

By: franklinanthony



1 Comment

How to make a uml using one class and one driver?

Im not sure at all how to do a uml but i have a project that I need to finsh that requires a uml.

The driver is

import java.util.Scanner;

public class DateClass
{
public static void main (String[] args)
{
String response;
do
{
int m1;
int m2;
int d1;
int d2;
int y1;
int y2;

Scanner scan = new Scanner(System.in);
System.out.println(”Enter a date (seperate with spaces) : “);

m1 = scan.nextInt();
d1 = scan.nextInt();
y1 = scan.nextInt();

Date first = new Date(m1, d1, y1);
System.out.println(”Enter other date (Seperate with spaces) : “);

m2 = scan.nextInt();
d2 = scan.nextInt();
y2 = scan.nextInt();

Date last = new Date (m2,d2, y2);
long difference = first.subtract(last);
System.out.println(”The number of days from “+first+ ” to ” +last+” is ” +difference);
System.out.println(”Are there any more dates that you would like to use? Y/N”);

response = scan.next();
response = response.toUpperCase();
}
while (response.equals(”Y”));

the class is

public class Date
{
private int month;
private int day;
private int year;

public Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
}

public boolean isLeap(int y)
{
if (y%4==0 && y%100!=0)
return true;
else if (y%100==0 && y%400==0)
return true;
else
return false;
}

public int daysInYear (int y)
{
if (isLeap (y))
return 366;
else
return 365;
}

public int daysInMonth (int m, int y)
{
if (m==1 ||m==3||m==5||m==7||m==8||m==10||m==12)
return 31;
else if (m==4||m==6||m==9||m==11)
return 30;
else if (m==2 && isLeap(y))
return 29;
else
return 28;
}

public String toString()
{
return month + ” ” + day + ” ” + year;
}

public long subtract (Date other)
{long total;
if (month==other.month && year==other.year)
total = other.year-day +1;
else if (year==other.year)
{
total = daysInMonth(month,year) - day+1;
for (int i = month+1; i total += daysInMonth (i,year);
total += other.day;
}
else
{
total = daysInMonth (month,year) - day +1;
for (int i = month + 1; i<=12; ++i)
total += daysInMonth(i, year);
for (int i = year +1; i total += daysInYear(i);
for (int i =1; i total += daysInMonth (i,other.year);
total += other.day;
}
return total;
}
}

By: fratisacat14



No Comments

Java random Unique numbers HELP ?

/*I am trying to generate 6 random unique (1-49) no.s and understand that my validation is incorrect.Help Please?*/

import java.util.*;
import javax.swing.JOptionPane;
public class ranUnique {

public static void main(String[] args) {

String output=”";
int[] arrayRan=new int[6];int ran2;
for(int ran=0;ran arrayRan[ran]=(int)(Math.random()*50
//validate
for(ran2=0;ran2<=ran;ran2++){
if ((arrayRan[ran]==arrayRan[ran2]) || (arrayRan[ran]==0)) {
arrayRan[ran]=(int)(Math.random()...
//ran=ran-1;
}

}
}
Arrays.sort(arrayRan);
for(int sort=0;sort output=output+ arrayRan[sort]+" ";
}
JOptionPane.showMessageDialog(null,ou...
}
}
Thnx for the suggestions...
as per deonejua alternative..it looks better than the math.random()..but it still does not give me unique numbers and thts wht I am actually having problems with..
as fir using the sets...I will have to keep it for the next semester ..thnx anyway..
And yes it seems like the same lottery modelling which has become a hugely queried topic in the java forums from newbies like me..hehe..hopefully for not too much a dismay for the weathered lots..
thnx for all the suggestion guys...i hve decided to validate it using a do while loop with a boolean method to validate duplicates..ta-da..might come back with more trivial queries...muahh

By: rabbitrun



No Comments

help with my java homework please errors?

the error i get is:

IllegalFormatConversionException: f != java.lang.Integer

it kept commenting out stuff to find where it was and i think its with year but i dont know how to fix it or why please help

my code:

//******************************************************
// Tara D
// CS1 — 10:00 —
//
// Program Convert: This program calculates and
// prints account balance for a bank account.
//******************************************************
// get numbers from a file, calculate a value for number
// of years passed since hurricane occured, put it in an
// output file, prompt user first and lastname from “console”
// read info from input file, store variables, dollar amounts
// displayed in 4 decimarl places, dont include dollar signs
// dollar amounts 17 characters wide, others 12 characters
// align dollar amounts and calculated years right, other
// left align, DONT FORGET COLUMN HEADINGS, when program
// finished running print 2 blank lines and a message that
// says name and that the program has completed successfully
//******************************************************

import java.util.*;
import java.io.*;
import javax.swing.JOptionPane;

public class hurricanes
{

static Scanner console = new Scanner(System.in);

public static void main (String[] args)throws FileNotFoundException
{

Scanner inFile = new Scanner(new FileReader(”Hurricanes.txt”));
PrintWriter outFile = new PrintWriter(”hurricane.out”);

//declare variables

String hName;
int year;
double damage;
String region;
double femaFunds;

int numYears;
String name;
int todayDate = 2008;
String hurricane = “Hurricane”;
String Year = “Year”;
String total = “Total Damage”;
String Region = “Region”;
String unusedfema = “Unused FEMA”;
String ysince = “Years Since”;

// read account information from file

hName = inFile.next();
year = inFile.nextInt();
damage = inFile.nextDouble();
region = inFile.next();
femaFunds = inFile.nextDouble();

//perform calculations

System.out.print(”Enter the year:”);
todayDate = console.nextInt();

numYears = year - todayDate;

//statements
System.out.print(”Enter your first and last name:”);
name = console.next();

outFile.printf (”%12s”, hurricane);
outFile.printf (”%12s”, Year);
outFile.printf (”%17s”, total);
outFile.printf (”%12s”, region);
outFile.printf (”%17s”, unusedfema);
outFile.printf (”%12s”, ysince);
outFile.printf (”%n”);

/*outFile.printf (” ——— %12s”);
outFile.printf(” —- %12f”);
outFile.printf(” ———— %17f”);
outFile.printf(” —— %12f”);
outFile.printf(” ———– %17f”);
outFile.printf(” ———– %12f”);
outFile.printf (”%n”);

outFile.printf (”%12s”, hName);
outFile.printf(”%12f”, year);
outFile.printf(”%17.4f”, damage);
outFile.printf(”%12f”, region);
outFile.printf(”%17.4f”, femaFunds);
outFile.printf(”%12f”, numYears);
outFile.printf (”%n”);*/

outFile.printf (”%12s”, hName);
//outFile.printf(”%12f”, year);
outFile.printf(”%17.4f”, damage);
outFile.printf(”%12s”, region);
outFile.printf(”%17.4f”, femaFunds);
outFile.printf(”%12f”, numYears);
outFile.printf (”%n”);

System.out.println(”");
System.out.println(”");
System.out.print(name + “, the formatting has been completed.”);

inFile.close(); // infile close
outFile.close(); // outfile close
}//public static close
}//class close
here:
//outFile.printf(”%12f”, year);
and here:
outFile.printf(”%12f”, numYears)
how do i make it not a float just take the f out im confused so sorry im just learning :-) also it errors when i run it, it compiles fine

By: Tara D



2 Comments

Programming Help (java)! Smart people needed?

My casino class won’t compile. When the user enters their name, I’m trying to make a new player object. I want to keep track of the player and allow them to play casino games. There may be something wrong with my class import statement. I’m not sure.

————————————–…

import java.util.Scanner;

public class player{

private String name;
private double balance;
Scanner reader;

public player(){
name = “”;
balance = 0;
reader = new Scanner(System.in);
}

public player(String n){
name = n;
balance = 50;
reader = new Scanner(System.in);
}

public String getName(){
return name;
}

public double getBalance(){
return balance;
}

}

————————————–

import player.class
import java.util.Scanner;

public class casino{

public static void main(String[] args){

Scanner scanner = new Scanner(System.in);
System.out.println(”Good day. What’s your name.”);
new casino(scanner.nextLine());
System.out.println(getName() + “, What would like to do?”);
}

}

By: John



1 Comment

I’m trying to get my Java program working?

My program is supposed to take 5 different products and keep up with how many of each of the 5 products are sold. It should display the total retail of the items that are sold. (using a sentinel-controlled)

* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;

public class MailHouse {

public static void main(String args[])
{

private int total;
private int iCounter;
private int 1Count;
private int 2Count;
private int 3Count;
private int 4Count;
private int 5Count;

// public MailHouse( String name)
// {
public void displayMessage()
{

System.out.printf( “Welcome to Mail House for\n%s!”);

}
public void inputProd()
{
Scanner input = new Scanner( System.in);

int product;

System.out.printf( “%s”,
“Enter an integer from 1-30″);

while (input.hasNext())
{
product = input.nextInt();
total += product;
++iCounter;

thingCounter( int product)

}
}

public void thingCounter( int product)
{

switch (product)
{

case 1: // product 1
total=(double)1Count*2.98;

break; //do this for case 1 thru 5

case 2:
total = (double)product*4.50;
2Count;
break;

case 3:
total = (double)product*9.98;
3Count;
break;

case 4:
total = (double)product*4.49;
4Count;
break;

case 5:
total = (double)product*6.87;
5Count;
break;
}
}
public void displayResults()
{
System.out.println( “\nResults:”);

if (iCounter != 0)
{

double fin = (double) total * iCounter;

System.out.printf( “Total of products entered is”, fin );
}
else
System.out.println( “No Products Entered” );
}
}

By: Dark Future



No Comments

java.util.Scanner problems in text pad?

import java.util.Scanner;
public class Salary
{
public static void main(String[] args)
{
final double OVERTIME = 1.5;

int overTimeHours;
double hourlyWage;
int hoursWorked;

Scanner read = new Scanner(System.in);

System.out.println(”please enter your hours worked”);
hoursWorked = read.nextInt();

System.out.println(”please enter your hourly wage”);
hourlyWage = read.nextDouble();

System.out.println(”your weekly wage without over time calculated = ” + hoursWorked * hourlyWage);

if(hoursWorked > 40)
{
overTimeHours = hoursWorked - 40;
hoursWorked = 40;
System.out.println(”your weekly wage with overtime calulated = ” + ((hoursWorked * hourlyWage) + (overTimeHours * OVERTIME * hourlyWage)));
}
}
}
this is a copy of code id done in my computer science class and my parents wanted to see it but its not identifing the Scanner class and making the code pointless because theres no input to give the variables a value
how can i fix it??
import java.util.Scanner;
public class Salary
{
public static void main(String[] args)
{
final double OVERTIME = 1.5;

int overTimeHours;
double hourlyWage;
int hoursWorked;

Scanner read = new Scanner(System.in);

System.out.println(”please enter your hours worked”);
hoursWorked = read.nextInt();

System.out.println(”please enter your hourly wage”);
hourlyWage = read.nextDouble();

System.out.println(”your weekly wage without over time calculated = ” + hoursWorked * hourlyWage);

if(hoursWorked > 40)
{
overTimeHours = hoursWorked - 40;
hoursWorked = 40;
System.out.println(”your weekly wage with overtime calulated = ” + ((hoursWorked * hourlyWage) + (overTimeHours * OVERTIME * hourlyWage)));
}
}
}
this is a copy of code id done in my computer science class its not identifing the Scanner class how can i fix it??

can the solution still fix it if im running in vista cuz its not picking javac as a command is there a different command used for it??

By: Jonathon I



1 Comment

Computer Programming Homework. Help please?

Traditional password entry schemes are susceptible to “shoulder surfing” in which an attacker watches an unsuspecting user enter their password or PIN number and uses it later to gain access to the account. One way to combat this problem is with a randomized challenge-response system. In these systems the user enters different information every time, based on a secret in response to a randomly generated challenge. Consider the following scheme, in which the password consists of a five-digit PIN number (00000 to 99999). Each digit is assigned a random number that is 1, 2, or 3. The user enters the random numbers that correspond to their PIN instead of their actual PIN numbers.

For example, consider an actual PIN number of 12345. To authenticate the user would be presented with a screen such as:

PIN: 0 1 2 3 4 5 6 7 8 9
NUM: 3 2 3 1 1 3 2 2 1 3

The user would enter 23113 instead of 12345. This doesn’t divulge the password even if an attacker intercepts the entry because 23113 could correspond to other PIN numbers, such as 69440 or 70439. The next time the user logs in, a different sequence of random numbers would be generated, such as:

PIN: 0 1 2 3 4 5 6 7 8 9
NUM: 1 1 2 3 1 2 2 3 3 3

Write a program to simulate the authentication process using this scheme. Store an actual PIN number in your program. The program should use an array to assign random numbers to the digits from 0 to 9. Output the random digits to the screen, input the response from the user, and output whether or not the user’s response correctly matches the PIN number.

To get you going I have included some starter code for you below. You only need to fill in the method isValid and invoke it within the if statement at the end of the main method.

Here is the source code as a .java file: Authenticate.java
Here is a completed, compiled class that you can run to see the desired behavior: Authenticate.class

import java.util.Scanner;

public class Authenticate
{
public static void main(String[] args)
{
// Actual password is 99508
int[] actual_password = {9, 9, 5, 0, 8};
// Array to hold randomly generated digits
int[] random_nums = new int[10];
// Array to hold the digits entered by the user to authenticate
int[] entered_digits = new int[actual_password.length];

// Randomly generate numbers from 1-3 for
// for each digit
for (int i=0; i < 10; i++)
{
random_nums[i] = (int) (Math.random() * 3) + 1;
}

// Output the challenge
System.out.println("Welcome! To log in, enter the random digits from 1-3 that");
System.out.println("correspond to your PIN number.");
System.out.println();
System.out.println("PIN digit: 0 1 2 3 4 5 6 7 8 9");
System.out.print("Random #: ");
for (int i=0; i<10; i++)
{
System.out.print(random_nums[i] + " ");
}
System.out.println();
System.out.println();

// Input the user's entry
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter code.");
String s = keyboard.next();
// Extract the digits from the code and store in the entered_digits array
for (int i=0; i {
entered_digits[i] = s.charAt(i) - '0'; // Convert char to corresponding digit
}
// At this point, if the user typed 12443 then
// entered_digits[0] = 1, entered_digits[1] = 2, entered_digits[2] = 4,
// entered_digits[3] = 4, and entered_digits[4] = 3

/****
TO DO: fill in the parenthesis for the if statement
so the isValid method is invoked, sending in the arrays
actual_password, entered_digits, and random_nums as
parameters
***/
if () // FILL IN HERE
{
System.out.println("Correct! You may now proceed.");
}
else
{
System.out.println("Error, invalid password entered.");
}
}

/****
TO DO: Fill in the body of this method so it returns true
if a valid password response is entered, and false otherwise.

For example, if:
actual = {9,9,5,0,8}
randnums = {1,2,3,1,2,3,1,2,3,1}

then this should return true if:
entered[0] == 1 (actual[0] = 9 -> randnums[9] -> 1)
entered[1] == 1 (actual[1] = 9 -> randnums[9] -> 1)
entered[2] == 3 (actual[2] = 5 -> randnums[5] -> 3)
entered[3] == 1 (actual[3] = 0 -> randnums[0] -> 1)
entered[4] == 3 (actual[4] = 8 -> randnums[8] -> 3)

or in other words, the method should return false if any of
the above are not equal.
****/
public static boolean isValid(int[] actual, int[] entered, int[] randnums)
{
/* TO DO: FILL IN CODE HERE */
return true;
}
}

Any suggestions would be greatly appreciated! Thanks!

By: ann



1 Comment