Input 2 names and output the average age - java

This is for personal knowledge of how this works, is not for school
Program requirements - Enter 2 Names. Have the program find the assigned values with the names and print the average between the two people.
I an not sure how to get the Scanner to take the input and go to the class to make it start processing. For example, in the main method if I sysout print a, it should display the string inside the method getName.
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
rainfall a = new rainfall();
rainfall b = new rainfall();
System.out.println(a);
// System.out.print("Please enter month one: ");
// Scanner = new Scanner(System.in);
// rain1 = aRain;
// System.out.print("Please enter month two: ");
// Scanner = new Scanner(System.in);
//
// int average = (rain1 + rain2) / 2;
// System.out.println("The average rainfall for " + var +
"and " + var2 +"is: " + average);
}
}
class rainfall {
String rainamt;
String Rain_Amount;
Scanner input = new Scanner(System.in);
String rainMonth = input.nextLine();
String rainAmount(String rainMonth) {
Rain_Amount = getName(rainMonth);
return Rain_Amount;
}
private String getName(String rainMonth) {
if (rainMonth.equals("Jan")) {
rainamt = "3.3";
}
else if (rainMonth.equals("Feb")) {
rainamt = "2.2";
}
else {
System.out.println("Not a valid month name");
}
return rainamt;
}
}

You only need to say Scanner scanner = new Scanner(System.in); once. Then you can use the scanner's nextLine() method to input data. It returns a string, so be sure to store the result in a variable.

I completed my program
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the first month: ");
String aMonth = input.nextLine();
System.out.print("Please enter the second month: ");
String bMonth = input.nextLine();
rainfall aRainfall = new rainfall();
String aName = aRainfall.rainAmount(aMonth);
Double aAmount = Double.parseDouble(aName);
rainfall bRainfall = new rainfall();
String bName = bRainfall.rainAmount(bMonth);
Double bAmount = Double.parseDouble(bName);
double Avg = (aAmount + bAmount) / 2;
System.out.println("\nIn the month of " + aMonth + " it had "
+ aAmount + " inches of rain.");
System.out.println("In the month of " + bMonth + " it had "
+ bAmount + " inches of rain.");
System.out.println("The average rainfall between the two months is: " + Avg);
}
}
class rainfall {
private String Rain_Amount;
String rainAmount(String rainMonth) {
Rain_Amount = getAmount(rainMonth);
return Rain_Amount;
}
private String getAmount(String rainMonth) {
if (rainMonth.equals("Jan")) {
Rain_Amount = "3.3";
}
else if (rainMonth.equals("Feb")) {
Rain_Amount = "2.3";
}
else {
System.out.println("Not a valid month name");
}
return Rain_Amount;
}
}

Related

How to calculate sum from user input inside while loop

I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..
My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class DailyExpensesMain {
public static void main(String[] args) {
ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
Scanner sc = new Scanner(System.in);
boolean isRunning = true;
System.out.println("Enter the date for which you want to record the expenses : ");
String date = sc.nextLine();
while(isRunning) {
System.out.println("Enter category: (quit to exit)");
String category = sc.nextLine();
if(category.equalsIgnoreCase("quit")) {
break;
}
System.out.println("Enter price: ");
double price = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details: ");
String detail = sc.nextLine();
DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
expenses.add(newExpense);
}
sc.close();
for(DailyExpenses u: newExpense) {
System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
" Detail: " + u.getExpenseDetail());
}
}
}
I still clueless on the situation

How to put scanner inside a method and its output on a different method

I want to ask the user through a scanner class but I want this scanner to be in a method named readInput() and the output on a different method named writeOutput() using gett-setter
this is my code below:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LaboratoryExercise2 gro = new LaboratoryExercise2();
String[] SecondQuestion;
System.out.println("Select the item your purchasing.");
String Product1 = sc.nextLine();
System.out.println("Enter the Quantity and price separated by SPACE.");
SecondQuestion = sc.nextLine().split(" ");
int Quantity1 = Integer.parseInt(SecondQuestion[0]);
double Price1 = Double.parseDouble(SecondQuestion[1]);
double Amount1 = 0;
Amount1 = Quantity1 * Price1;
int Quantity = 0 + Quantity1;
double Amount = 0 + Amount1;
double Price = 0 + Price1;
I want the output of this to show on a different method
gro.setGrocery(Price, Quantity, Amount);
System.out.println("You've selected " + gro.getitemQuantity() + " " + Product1 + " " + "at " + " " +
gro.getitemPrice() + " each");
System.out.println("Amount due is " + gro.getamountDue());
This is my whole code:
import java.util.Scanner;
public class LaboratoryExercise2 {
private double itemPrice;
private int itemQuantity;
private double amountDue;
public void setGrocery(double newitemPrice, int newitemQuantity, double newamountDue) {
itemPrice = newitemPrice;
itemQuantity = newitemQuantity;
amountDue = newamountDue;
}
public double getitemPrice() {
return itemPrice;
}
public int getitemQuantity() {
return itemQuantity;
}
public double getamountDue() {
return amountDue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LaboratoryExercise2 gro = new LaboratoryExercise2();
String[] SecondQuestion;
System.out.println("Select the item your purchasing.");
String Product1 = sc.nextLine();
System.out.println("Enter the Quantity and price separated by SPACE.");
SecondQuestion = sc.nextLine().split(" ");
int Quantity1 = Integer.parseInt(SecondQuestion[0]);
double Price1 = Double.parseDouble(SecondQuestion[1]);
double Amount1 = 0;
Amount1 = Quantity1 * Price1;
int Quantity = 0 + Quantity1;
double Amount = 0 + Amount1;
double Price = 0 + Price1;
gro.setGrocery(Price, Quantity, Amount);
System.out.println("You've selected " + gro.getitemQuantity() + " " + Product1 + " " + "at " + " " +
gro.getitemPrice() + " each");
System.out.println("Amount due is " + gro.getamountDue());
}
}
Piling all your code into main is a bad idea. Java is object oriented, and main, being static, isn't.
The solution for sharing data between methods is usually to make a field.
class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
private Scanner scanner;
void go() throws Exception {
scanner = new Scanner(System.in);
scanner.useDelimiter("\\R");
int quantity = askInt("Enter the quantity: ");
}
private int askInt(String prompt) {
while (true) {
System.out.print(prompt);
if (scanner.hasNextInt()) return scanner.nextInt();
scanner.next(); // eat the non-int token
System.out.println("ERROR: Please enter an integer number.");
}
}
}
That's what virtually all command line java apps should look like: a one-liner main method, no use of static anywhere except main, a scanner field, set with the proper delimiter (\\R, which means .nextX() always reads one line worth of input; use .next() to read an entire line. Don't call .nextLine(), ever. nextLine() and all the other next methods interact in nasty ways that make scanner useless or at least unwieldy and bugprone for command line 'prompting', which why you do it this way.

Java grades exercise

I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

Why does this for loop run infinitely after recieving input? (Java)

Okay so this code asks the user to enter a name, year, and gender, and displays the ranking of the name for the selected year. It reads data from the url and places it into a map for each year. These maps are then placed into an array, and finally the rank is displayed to the user. My program never finishes running after entering the while loop. Here is the code:
public static void main(String[] args) throws MalformedURLException, IOException {
Scanner input = new Scanner(System.in);
Map[] boyArray = new Map[10];
Map[] girlArray = new Map[10];
System.out.print("Enter year (between 2001 and 2010): ");
String year = input.nextLine();
System.out.print("Enter gender (M or F): ");
String gender = input.nextLine();
System.out.print("Enter name: ");
String name = input.nextLine();
for (int i = 0; i < 10; i++) {
Map<String, String> boys = new HashMap<>();
Map<String, String> girls = new HashMap<>();
try {
java.net.URL url = new java.net.URL("http://www.cs.armstrong.edu/liang/data/babynamesranking"+ year + ".txt");
Scanner urlInput = new Scanner(url.openStream());
while (urlInput.hasNext()) {
String rank = input.next();
boys.put(urlInput.next(), rank);
urlInput.next();
girls.put(input.next(), rank);
urlInput.next();
}
}
catch (IOException ex) {
}
boyArray[i] = boys;
girlArray[i] = girls;
}
if (gender.charAt(0) == 'M') {
System.out.println("The name " + name + " was ranked " + boyArray[Integer.parseInt(year) - 2001].get(name) + " in " + year);
} else {
System.out.println("The name " + name + " was ranked " + girlArray[Integer.parseInt(year) - 2001].get(name) + " in " + year);
}
}
}
It looks like, as #uthark has already noted, your program is waiting for input because in your while loop you're waiting for input from System.in with the line String rank = input.next(); (and the line girls.put(input.next(), rank);). You probably meant to write String rank = urlInput.next(); and girls.put(urlInput.next(), rank); instead so that the rank and girl name come from http://www.cs.armstrong.edu/liang/data/babynamesrankingYYYY.txt.

Method to display records.

Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.

Categories

Resources