code is just continue looping.How to solve? - java

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

Related

Bubble sort and input

I have to enter 3 jumpers who will jump 2 times.
Here is an illustration via my console for the first jump. (it's step is ok)
Then, for the second jump. I have to sort the first jump from the smallest to the biggest.
So, I have to retrieve the jumper Emilie and not Olivia.
I don't understand how to do this ?
I think my problem is my sortBublle() method ?
import java.util.*;
class Main {
public static void main(String[] args) {
String[] arrayJumper = new String[3];
int[] arrayJump = new int[3];
encoding_jump_1(arrayJumper, arrayJump);
sortBublle(arrayJump);
encoding_jump_2(arrayJumper, arrayJump);
}
public static void encoding_jump_1(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJumper = 0;
int iJump = 0;
System.out.println("Jump 1 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter jumper " + (i+1) + " : ");
String jumper = input.next();
arrayJumper[iJumper++] = jumper;
System.out.print("Enter for the jumper " + arrayJumper[i] + " the first jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
public static void sortBublle(int[] arrayJump){
int size = arrayJump.length;
int tempo = 0;
for(int i=0; i<size; i++){
for(int j=1; j < (size - i) ; j++){
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
}
}
}
}
public static void encoding_jump_2(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJump = 0;
System.out.println("Jump 2 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter for the jumper " + arrayJumper[i] + " the second jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
}
Thank you very much for your help.
You are only sorting arrayJump --> You need to sort both arrayJumper and arrayJump`
...
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
tempName = arrayJumper[j-1];
arrayJumper[j-1] = arrayJumper[j];
arrayJumper[j] = tempName;
}

applying lambda expression in java

Here's my code.I'm not yet familliar with lambda expressions in java 8.
I'd like to apply a lambda expression here doing a random generation of healthy and unhealthy horses.
Then I'll print and run only the healthy horses. How can I do that?
import java.util.Scanner;
import java.util.Random;
public class HorseRace {
static int numHorse = 0;
static int healthyHorse = 0;
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
Horse[] horseArray = new Horse[numHorse];
while (counter < horseArray.length) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
horseArray[counter] = new Horse(warCry);
horseArray[counter].setName(horseName);
System.out.println(horseArray[counter]);
System.out.println(this);
System.out.println(healthyHorse);
//unhealthyHorse++;
}
counter++;
}
System.out.println(horseArray.length);
System.out.println("...Barn to Gate...");
for (int i = 0; i < healthyHorse; i++) {
horseArray[i].start();
}
}
}
I have refactored some of the code and used Lambda expressions wherever possible.
public class HorseRace {
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
int numHorse;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
List<Horse> horses = new ArrayList<>();
while (counter < numHorse) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
Horse horse = new Horse(warCry);
horse.setName(horseName);
horses.add(horse);
}
counter++;
}
horses.forEach(horse -> {
System.out.println(horse);
System.out.println(0);
});
System.out.println(horses.size());
System.out.println("...Barn to Gate...");
horses.forEach(Horse::start);
}
}
Lambda expression is used as below:

Java: Functions for doing a project

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);

How to use 2D arrays with other classes

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;
}

Input String and int in the same line

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]);

Categories

Resources