I'm here doing an assignment and I'm getting a problem
A red mark is coming up next to "TotalCharge = ptr.calculateCharge(NightsStay, perNight);" and the error is double cannot be converted to Integer.
I tried researching to solve the problem but nothing is working.
Thank you very much.
HiibiscusHotelSpa9674 ptr = new HiibiscusHotelSpa9674();
Scanner keyboard = new Scanner(System.in);
Integer compare = 0;
String response = null;
String number = null;
Double Price = 0.00;
Integer TotalCharge = 0;
Integer ItemNo = 0;
String surName;
Integer perNight = 0;
Integer roomNumber = 0;
Double amountPaid = 0.0;
String temp = null;
String Name = null;
Double cashPaid = 0.0;
Double Change = 0.0;
Integer NightsStay = 0;
temp = JOptionPane.showInputDialog("Enter The amount of Items :");
int Size = Integer.parseInt(temp);
String[] ItemName = new String[Size];
Integer[] ItemId = new Integer[Size];
double[] ItemPrice = new double[Size];
Integer index = 0;
while (index < Size) {
ItemName[index] = JOptionPane.showInputDialog("Enter The Item Name:");
temp = JOptionPane.showInputDialog("Enter Item ID for " + ItemName[index] + " :");
ItemId[index] = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Enter The Price for " + ItemName[index] + " :");
ItemPrice[index] = Double.parseDouble(temp);
index++;
ptr.displayMenu(ItemName, ItemId, ItemPrice);
Name = ptr.getDataSetA();
cashPaid = ptr.getDataSetB(ItemId);
Change = ptr.performCalc(cashPaid, ItemPrice);
ptr.displayResults(Change, cashPaid);
response = JOptionPane.showInputDialog("Sale Complete? Enter Y or N: ");
switch (response) {
case "N":
perNight = ptr.GetGuestInfo();
NightsStay = ptr.GetDate();
TotalCharge = ptr.calculateCharge(NightsStay, perNight);
ptr.displayGuestBill(NightsStay, TotalCharge);
break;
case "n":
perNight = ptr.GetGuestInfo();
NightsStay = ptr.GetDate();
TotalCharge = ptr.calculateCharge(NightsStay, perNight);
ptr.displayGuestBill(NightsStay, TotalCharge);
break;
default:
JOptionPane.showMessageDialog(null, "Thank you very much and haave a wonderful day!");
}
public void displayMenu(String Name[], Integer ItemId[], double Price[]) {
System.out.printf("Item Name Item ID ItemPrice\n");
for (int i = 0; i < Name.length; i++) {
System.out.printf("%s\t %d\t %.2f\t\n", Name[i], ItemId[i], Price[i]);
}
}
public String getDataSetA() {
Scanner keyboard = new Scanner(System.in);
String[] personalInformation = new String[2];
String NameRoomNumber = null;
System.out.printf("Please Enter Room Number\n");
personalInformation[1] = keyboard.next();
System.out.printf("Enter your Surname\n");
personalInformation[0] = keyboard.next();
String NameNumber = Arrays.toString(personalInformation);
return NameRoomNumber;
}
private Double getDataSetB(Integer[] ItemId) {
Scanner keyboard = new Scanner(System.in);
String temp = null;
for (int i = 0; i < ItemId.length; i++) {
double cashPaid = 0.0;
Integer[] Items = new Integer[ItemId.length];
System.out.println("Please Enter the Item ID for the item");
ItemId[i] = keyboard.nextInt();
}
System.out.printf("Please Enter Cash Paid\n");
double cashPaid = keyboard.nextDouble();
return cashPaid;
}
private double performCalc(double cashPaid, double[] Price) {
Scanner keyboard = new Scanner(System.in);
double Cost = 0.0;
double change = 0.0;
double moneyOwe = 0.0;
for (int i = 0; i < Price.length; i++) {
Cost = Cost + Price[i];
}
if (cashPaid < Cost) {
moneyOwe = Cost - cashPaid;
JOptionPane.showMessageDialog(null, "You are $" + moneyOwe + " short");
} else {
change = cashPaid - Cost;
}
return change;
}
private void displayResults(Double Change, Double cashPaid) {
JOptionPane.showMessageDialog(null, "Cash Paid:$ " + cashPaid + "Change:$ " + Change + ".");
}
private Integer GetGuestInfo() {
String temp = null;
String Guestname = null;
Integer FloorNum = 0;
Integer NoofPer = 0;
Guestname = JOptionPane.showInputDialog("Please Enter Guest Name");
temp = JOptionPane.showInputDialog("Enter Floor Required");
FloorNum = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please Enter The Number of Persons Staying with you");
NoofPer = Integer.parseInt(temp);
return NoofPer;
}
private Integer GetDate() {
String temp = null;
Integer day = 0;
Integer month = 0;
Integer year = 0;
Integer Nights = 0;
temp = JOptionPane.showInputDialog("Please enter the Day: ");
day = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the Month: ");
month = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the Year: ");
year = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the number of Nights staying:");
Nights = Integer.parseInt(temp);
return Nights;
}
private Double calculateCharge(Integer amtofNights, Integer perNight) {
Integer floor = 0;
double totalCharge = 0.0;
if (floor > 4) {
// int perNight = 0;
int Numofnights = 0;
totalCharge = 150 * perNight * amtofNights;
} else {
totalCharge = 100 * perNight * amtofNights;
}
return totalCharge;
}
private void displayGuestBill(Integer NightsStayed, Integer totalCharge) {
System.out.printf("The total number of nights:%d\n", NightsStayed);
System.out.printf("The total Charge:%d", totalCharge);
}
}
Double is a wrapper class on top of the primitive double. It can be cast to double, but it cannot be cast to int directly.
If you use double instead of Double, it will compile:
double d = 10.9;
int i = (int)(d);
You can not convert a double to an integer implictely, because you are loosing precision. Imagine converting 3.7 to an integer, you would get 3 but a significant amount of information got lost.
If you are fine with this, you can do an explicit cast with (int)some_double for example.
Your code example does not contain any types, which makes it hard to say at which place your conversion happens.
Edit: Since your code example now contains types, it looks likely that your calculateCharge returns a double, but you are storing it into an integer.
You should force the explicit cast by doing
TotalCharge = (int)ptr.calculateCharge(NightsStay, perNight);
Related
I have an assignment, I was wondering how I could go about using 2D arrays with another class, I have a class called Die that looks like this:
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now in a main method i have to do the following
I have all the other parts done, I just cant seem to figure out this part.
My current code(Not started this part) is below
import java.util.Arrays;
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
String[] playerNames = new String[playerCount];
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
playerNames[i] = scan.nextLine();
}
int randomNum = (int)(Math.random() * (30-10)) +10;
}
}
Do any of you java geniuses have any advice for me to begin?
Thanks!
Here is your main method, you just need to update your main method with this one,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
HashMap<String, ArrayList<Die>> hashMap = new HashMap<String, ArrayList<Die>>();
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
hashMap.put(scan.nextLine(),new ArrayList<Die>());
}
for(String key : hashMap.keySet()){
System.out.println(key + "'s turn....");
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
hashMap.get(key).add(d);
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(hashMap.get(key).size()>4){System.out.println("Sorry, Maximum 5-Try you can...!!!");break;}
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
hashMap.get(key).add(dd);
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
for(String key : hashMap.keySet()){
System.out.println(key + " - " + hashMap.get(key));
}
}
EDITED
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++){
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(totalRollDie < 5){ // if user want one more time to roll die then first check whether alread user has rolled 5-time or not.
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ; // rolled and print whatever value get..
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++){
finalDie[i][var] = tempDie[var]; // store Die object into finalDie array which can random number for all user..
}
}
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i]){
System.out.println(de);
}
}
tempDie = null;
}
I was wondering if someone could tell me
1. why, when i input weightNumber with a decimal place, weightConverted doesn't convert it to the whole number, even though I create variable for it?
2. how could i improve this "program" in any way, THANK YOU !!
here is the problem:
code:
import java.util.Scanner;
public class cofee {
public static void main (String []args){
double weightNumber = 0;
String packageType = "";
String serviceType ="";
double totalFee = 0;
double weightConverted = Math.round(weightNumber); // <- this is the problem, should i put it somewhere else?
final double LETTERCOSTP = 12.00;
final double LETTERCOSTS = 10.50;
final double BOXCOSTP = 15.75;
final double BOXCOSTS = 13.75;
final double BOXWEIGHTP = 1.25;
final double BOXWEIGHTS = 1.00;
// input
Scanner input = new Scanner(System.in);
System.out.print("Enter package type (letter/box): ");
packageType = input.nextLine().toLowerCase();
System.out.print("Enter type of service (standard/priority): ");
serviceType = input.nextLine().toLowerCase();
switch(packageType)
{
case "letter":
System.out.print("Enter the weight in ounces: ");
weightNumber = input.nextDouble();
break;
case "box":
System.out.print("Enter the weight in pounds: ");
weightNumber = input.nextDouble();
break;
default:
System.out.print("WRONG PACKAGE TYPE !!!");
}
// letter
if (packageType.equals("letter") && serviceType.equals("priority"))
{
totalFee = LETTERCOSTP;
}
if (packageType.equals("letter") && serviceType.equals("standard"))
{
totalFee = LETTERCOSTS;
}
// box
if (packageType.equals("box") && serviceType.equals("priority"))
{
totalFee = BOXCOSTP + ((weightConverted - 1.0) * BOXWEIGHTP);
}
if (packageType.equals("box") && serviceType.equals("standard"))
{
totalFee = BOXCOSTS + ((weightConverted - 1.0) * BOXWEIGHTS);
}
// display
System.out.println("The fee is € "+ totalFee + " for a package with");
System.out.println("\tType: "+packageType);
System.out.println("\tService: "+serviceType);
System.out.println("\tOunces: "+weightConverted);
}
}
The line double weightConverted = Math.round(weightNumber); will call round() with the value of weightNumber, which is 0, so it rounds 0 to... well... 0, and assigns it to weightConverted.
How can I input a String and an int in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
I expect the output will be like this
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25
Result: John 45
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);
This is the array i want to put to another array.
String [][]roomType = new String[4][4];
roomType[0][0] = "Standard";
roomType[0][1] = "500";
roomType[0][2] = "5";
roomType[0][3] = "1";
roomType[1][0] = "Double";
roomType[1][1] = "800";
roomType[1][2] = "4";
roomType[1][3] = "2";
roomType[2][0] = "Matrimonial";
roomType[2][1] = "3500";
roomType[2][2] = "6";
roomType[2][3] = "3";
roomType[3][0] = "Triple";
roomType[3][1] = "4500";
roomType[3][2] = "5";
roomType[3][3] = "4";
/*-----------------------------------------------------------------
* Costumer's Information
-----------------------------------------------------------------*/
do{//Start Of First Loop - Customer's Info
System.out.print("\nEnter Number Of Records : ");
int Records = Integer.parseInt(br.readLine());
String [][] customer = new String [Records][7]; //records for customer
for (int x = 0; x < Records; x++){ // Start For Records
System.out.print("\nConfimation Number: ");
customer[x][0] = br.readLine();
System.out.print("\nFirst Name: ");
customer[x][1] = br.readLine();
System.out.print("Last Name: ");
customer[x][2] = br.readLine();
System.out.print("Guest: ");
customer[x][3] = br.readLine();
System.out.print("Night: ");
customer[x][4] = br.readLine();
System.out.println();
System.out.print("1. Standard..............................................P500.00\n");
System.out.print("2. Double................................................P800.00\n");
System.out.print("3. Matrimonial...........................................P3,500.00\n");
System.out.print("4. Triple................................................P4,500.00 \n");
System.out.print("\n\nPlease Select Room Type: ");
int SwitchOne = Integer.parseInt(br.readLine());
int two = SwitchOne;
switch(SwitchOne){
case 1:
case 2:
case 3:
case 4:
Here is the process to put an array to another array or to assign value to an array from array.
for(int row=SwitchOne-1;row<4;row++){
int roomID = Integer.parseInt(roomType[row][3]);
if(two == roomID){
double price = Double.parseDouble(roomType[row][1]);
int available = Integer.parseInt(roomType[row][2]);
available -= 1;
String avail = Double.toString(available);
roomType[row][2] = avail;
customer[x][5] = roomType[row][0];
double guest = Double.parseDouble(customer[x][3]);
guest *= GuestRate;
double night = Double.parseDouble(customer[x][4]);
price *= night;
double totalAmount = guest + price;
String AmountTotal = Double.toString(totalAmount);
customer[x][6] = AmountTotal;
}
}
The problem is when the first array that has been put cannot be used again. the compiler says its OutOfBounds.
so i cannot choose what that has been chosen before.
I'm new at Java class, lend me some help.
This is 1 method class only.
i cant understand 2 or more methods.
just comment if you don't understand it, its too hard to explain.
If you want assign two Dimensional Array from one to another one.
Follow the below code snippet,
String[][] newArray = new String[roomType[0].length][roomType[1].length];
for (int i = 0; i < roomType[0].length; i++){
for (int j = 0; j < roomType[1].length; j++){
newArray[i][j] = roomType[i][j];
}
}
If you want cross-check try this one, whether the array correctly assigned, try the below one,
for (int i = 0; i < newArray[0].length; i++){
for (int j = 0; j < newArray[1].length; j++){
System.out.print(newArray[i][j] + " ");
}
System.out.println("");
}
Try this,
import java.io.*;
public class ArrayTest {
public static void main(String args[]) throws NumberFormatException,
IOException {
double GuestRate = 100;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[][] roomType = new String[4][4];
roomType[0][0] = "Standard";
roomType[0][1] = "500";
roomType[0][2] = "5";
roomType[0][3] = "1";
roomType[1][0] = "Double";
roomType[1][1] = "800";
roomType[1][2] = "4";
roomType[1][3] = "2";
roomType[2][0] = "Matrimonial";
roomType[2][1] = "3500";
roomType[2][2] = "6";
roomType[2][3] = "3";
roomType[3][0] = "Triple";
roomType[3][1] = "4500";
roomType[3][2] = "5";
roomType[3][3] = "4";
/*-----------------------------------------------------------------
* Costumer's Information
-----------------------------------------------------------------*/
// Start Of First Loop - Customer's Info
System.out.print("\nEnter Number Of Records : ");
int Records = Integer.parseInt(br.readLine());
String[][] customer = new String[Records][7]; // records for customer
int available;
for (int x = 0; x < Records; x++) { // Start For Records
System.out.print("\nConfimation Number: ");
customer[x][0] = br.readLine();
System.out.print("\nFirst Name: ");
customer[x][1] = br.readLine();
System.out.print("Last Name: ");
customer[x][2] = br.readLine();
System.out.print("Guest: ");
customer[x][3] = br.readLine();
System.out.print("Night: ");
customer[x][4] = br.readLine();
System.out.println();
System.out
.print("1. Standard..............................................P500.00\n");
System.out
.print("2. Double................................................P800.00\n");
System.out
.print("3. Matrimonial...........................................P3,500.00\n");
System.out
.print("4. Triple................................................P4,500.00 \n");
System.out.print("\n\nPlease Select Room Type: ");
int SwitchOne = Integer.parseInt(br.readLine());
int two = SwitchOne;
int row = SwitchOne - 1;
int roomID = Integer.parseInt(roomType[row][3]);
if (two == roomID) {
double price = Double.parseDouble(roomType[row][1]);
available = Integer.parseInt(roomType[row][2]);
if( Integer.parseInt(roomType[row][2]) >= Integer.parseInt(customer[x][3]))
{
available = available-Integer.parseInt(customer[x][3]);
String avail = Integer.toString(available);
roomType[row][2] = avail;
customer[x][5] = roomType[row][0];
double night = Double.parseDouble(customer[x][4]);
double guest = Double.parseDouble(customer[x][3]);
guest *= GuestRate * night;
price *= night;
double totalAmount = guest + price;
String AmountTotal = Double.toString(totalAmount);
customer[x][6] = AmountTotal;
System.out.println(customer[x][6]);
}
else
System.out.println("Room is not available for "+ customer[x][3]+ " Guests : We have only "+available+ " vacancy in that room");
}
}
}
}
It's working.. And the output is,
Enter Number Of Records : 3
Confimation Number: 1
First Name: f
Last Name: g
Guest: 2
Night: 2
Standard..............................................P500.00
Double................................................P800.00
Matrimonial...........................................P3,500.00
Triple................................................P4,500.00
Please Select Room Type: 1
5
1400.0
Confimation Number: 2
First Name: e
Last Name: r
Guest: 2
Night: 2
Standard..............................................P500.00
Double................................................P800.00
Matrimonial...........................................P3,500.00
Triple................................................P4,500.00
Please Select Room Type: 1
3
1400.0
Confimation Number: 3
First Name: d
Last Name: g
Guest: 2
Night: 2
Standard..............................................P500.00
Double................................................P800.00
Matrimonial...........................................P3,500.00
Triple................................................P4,500.00
Please Select Room Type: 1
1
Room is not available for 2 Guests : We have only 1 vacancy in that room
import java.util.Scanner;
public class TestPerson
{
/**
* Creates a new instance of <code>TestPerson</code>.
*/
public TestPerson()
{
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Menus[] menu = { new Menus("Add Member") };
MemberType[] m = { new MemberType("Corporate Member"), new MemberType("VIP Member") };
Clubs[] c = { new Clubs("Yoga", "Miss AA"), new Clubs("Kick-boxing", "Mr.AA"), new Clubs("aerobics", "Mrs.Wendy") };
RegMember[] r = new RegMember[1];
Cmember cm;
Vipmember vip;
Scanner s = new Scanner(System.in);
int choice = 0;
for (int z = 0; z < menu.length; z++)
{
System.out.println((z + 1) + ". " + menu[z].toString());
}
System.out.println("\nEnter Your selection:");
int choice = s.nextInt();
while (choice == 1)
{
for (int i = 0; i < r.length; i++)
{
System.out.println("\nYour reg no is :" + (RegMember.getNextNo() + 1));
for (int a = 0; a < m.length; a++)
{
System.out.println((a + 1) + ". " + m[a].toString());
}
System.out.println("\nEnter Your selection:");
int sel = s.nextInt();
if (sel == 1)
{
s.nextLine();
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Company Name:");
String CompanyName = s.nextLine();
String memberType = "Corporate Member";
for (int b = 0; b < c.length; b++)
{
System.out.println((b + 1) + ". " + c[b].toString());
}
System.out.println("\nEnter Your selection:");
int sel2 = s.nextInt();
String clubs = "Yoga";
cm = new Cmember(Name, Hpnum, age, CompanyName, memberType, clubs);
r[i] = new RegMember(cm);
}
else
{
s.nextLine();
System.out.println("---You will get a free exercise class---");
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Email:");
String email = s.next();
String memberType = "VIP Member";
vip = new Vipmember(Name, Hpnum, age, email, memberType);
r[i] = new RegMember(vip);
}
s.nextLine();
}
}
displayInfor(r);
}
public static void displayInfor(RegMember[] r)
{
for (int i = 0; i < r.length; i++)
System.out.println(r[i].toString());
}
}
I am a beginner for java. I am facing the problem that my code is continue looping.How to solve it?? thank you.
Your choice variable is never set to not = 1. Therefore the while loop will continue to run forever.
edit: With the amount of log messages in that code you should be able to see where surely.
If you are using If statements as such why not just alter the choice variable manually.
Anyway its too vague your question specify which loop and it would be easier to help