applying lambda expression in java - 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:

Related

How can I get the random numbers to print on the same line (for ex: 2, 10, 30, 25,14)

import java.util.Random;
import java.util.Scanner;
public class LuckyForLife {
public static int randomNum(int min, int max){
Random lotterynum = new Random();
int randomNum = lotterynum.nextInt((max-min)+1)+min;
return randomNum;
}
//**********************************************
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.equalsIgnoreCase("Y");
}
//**********************************************
public static void main(String args[]) {
final String TITLE = "Lucky For Life Lottery";
final String CONTINUE_PROMPT = "Do this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
for(int counter=1; counter<=5; counter++) {
System.out.printf("Your Lucky For Life Cash numbers are: " + randomNum(1,43));
System.out.println(" Your Lucky Ball number is: " + randomNum(1,43));
}
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
}
I am trying to get all the random values to print on one line so it looks like a list rather than the program executing 5 times.
(Ex: Your numbers are 5, 10 , 15, 34, 41)
You may use an array to store the random numbers, then use a StringBuilder to build the final sentence :
public static void main(final String args[]) {
final String TITLE = "Lucky For Life Lottery";
final String CONTINUE_PROMPT = "Do this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
int totalNumbers = 5;
int[] numbers = new int[totalNumbers];
do {
for (int counter = 0; counter < totalNumbers; counter++) {
numbers[counter] = randomNum(1, 43);
}
StringBuilder builder = new StringBuilder();
builder.append("Your Lucky For Life Cash numbers are: ");
for (int number : numbers) {
builder.append(number);
builder.append(' ');
}
System.out.println(builder);
System.out.println("Your Lucky Ball number is: " + randomNum(1, 43));
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
I changed a little your code, take a look if this would work for your need.
import java.util.Random;
import java.util.Scanner;
public class LuckyForLife {
private static final String TITLE = "Lucky For Life Lottery";
private static final int MIN_RANDOM_INT = 1;
private static final int MAX_RANDOM_INT = 43;
public static void main(String[] args) {
System.out.println("Welcome to "+ TITLE);
String continueAnwser = "Y";
Scanner inputUser = new Scanner(System.in);
try {
while ("Y".equalsIgnoreCase(continueAnwser)) {
System.out.println("How many number do you wish to generate?");
int numberOfElementsTogenerate = inputUser.nextInt();
String randomNumbers = generateRandomNumbersAsString(numberOfElementsTogenerate);
System.out.println("Your Lucky Ball number is:"+ randomNumbers);
System.out.println("Do this again? [y/N]:");
continueAnwser = inputUser.next();
}
System.out.println("Thank you for using " + TITLE);
} finally {
if (inputUser != null) {
inputUser.close();
}
}
}
private static String generateRandomNumbersAsString(int numberOfElementsTogenerate) {
Random random = new Random();
StringBuilder numersGeneratedBuider = new StringBuilder();
numersGeneratedBuider.append("[");
for (int i = 0; i < numberOfElementsTogenerate; i++) {
numersGeneratedBuider.append(random.nextInt((MAX_RANDOM_INT - MIN_RANDOM_INT) + 1) + MIN_RANDOM_INT);
if (i < numberOfElementsTogenerate-1) {
numersGeneratedBuider.append(",");
}
}
numersGeneratedBuider.append("]");
return numersGeneratedBuider.toString();
}
}

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

Object Array in JAVA giving InputMismatchException

Code and Snap of the Exception are attached. Pls Help me out with InputMismatchException. I believe there is something wrong while entering the value at runtime
import java.util.Scanner;
class ObjectArray
{
public static void main(String args[])
{
Scanner key=new Scanner(System.in);
Two[] obj=new Two[3];
for(int i=0;i<3;i++)
{
obj[i] = new Two();
obj[i].name=key.nextLine();
obj[i].grade=key.nextLine();
obj[i].roll=key.nextInt();
}
for(int i=0;i<3;i++)
{
System.out.println(obj[i].name);
}
}
}
class Two
{
int roll;
String name,grade;
}
Instead of :
obj[i].roll=key.nextInt();
Use:
obj[i].roll=Integer.parseInt(key.nextLine());
This ensures the newline after the integer is properly picked up and processed.
use Integer.parseInt(key.nextLine());
public class ObjectArray{
public static void main(String args[]) {
Scanner key = new Scanner(System.in);
Two[] obj = new Two[3];
for (int i = 0 ; i < 3 ; i++) {
obj[i] = new Two();
obj[i].name = key.nextLine();
obj[i].grade = key.nextLine();
obj[i].roll = Integer.parseInt(key.nextLine());
}
for (int i = 0 ; i < 3 ; i++) {
System.out.println("Name = " + obj[i].name + " Grade = " + obj[i].grade + " Roll = " + obj[i].roll);
}
}
}
class Two {
int roll;
String name, grade;
}
output
a
a
1
b
b
2
c
c
3
Name = a Grade = a Roll = 1
Name = b Grade = b Roll = 2
Name = c Grade = c Roll = 3

code is just continue looping.How to solve?

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

How can I fix this "OutOfBoundaryException" error?

import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();

Categories

Resources