Recall use input to perform certain tasks - java

It's a bit of a read, but I need to reuse the user input, is there a method I can use to manipulate the data input by the user.
Also for some reason when I output the total at the end it gives me an accumulated sum for each entry, i just need the total.
import java.util.*;
public class Account {
String Name = NewCamper.getCamperName();
private static double balance;
Account(){
balance = 0.0;
}
Account(String aFname, String aLname){
aFname = NewCamper.first;
aLname = NewCamper.last;
}
public void deposit(double amountDep){
balance=balance+amountDep;
}
private double oldBalance(){
return(Account.balance);
}
private double newBalance(double total){
return(balance-total);
}
public static void main(String args[]){
do{
System.out.println("Credit Camper Account? (yes/no)");
Scanner q =new Scanner(System.in);
String uq = q.nextLine();
if (uq.equalsIgnoreCase("yes")){
System.out.println("How much to credit?");
double c = q.nextDouble();
Account camp1 = new Account();
camp1.deposit(c);
System.out.println("Camper Credit: " + c);
}
else if(uq.equalsIgnoreCase("no")){
System.out.println(Account.balance);
}
else{
System.out.println("Invalid Response");
continue;
}
break;
}while(true);
List<String> transactions=new ArrayList<String>();
List<Double> amount=new ArrayList<>();
do{
System.out.println("Enter a Transaction: ");
Scanner tInput =new Scanner(System.in);
Scanner dInput =new Scanner(System.in);
String a =tInput.nextLine();
transactions.add(a);
System.out.println("Enter purchase amount: ");
double b =dInput.nextDouble();
amount.add(b);
System.out.println("Do you have new record ?(yes/no)");
String answer= tInput.nextLine();
if(answer.equalsIgnoreCase("Yes")){
continue;
}
break;
}while(true);
for (int i = 0; i < transactions.size(); i++) {
System.out.println(transactions.get(i));
}
System.out.println(transactions+" (£)"+amount);
System.out.println("Input Camper First Name: ");
Scanner afn = new Scanner(System.in);
String af = afn.nextLine();
System.out.println("Input Camper Surname: ");
Scanner aln = new Scanner(System.in);
String al = afn.nextLine();
NewCamper.first = af;
NewCamper.last = al;
System.out.println(af+" "+al+" 's transactions:"+transactions);
System.out.println(af+" "+al+" 's purchase amounts:"+amount);
double total=0.0d;
for(int counter = 0; counter<amount.size(); counter++){
total+=amount.get(counter);
System.out.println("Total Price: £"+ total);
}
}
}

Change this:
double total=0.0d;
for(int counter = 0; counter<amount.size(); counter++){
total+=amount.get(counter);
System.out.println("Total Price: £"+ total);
}
to:
double total=0.0d;
for(int counter = 0; counter<amount.size(); counter++){
total+=amount.get(counter);
}
System.out.println("Total Price: £"+ total);
Shouldn't come as a surprise that putting an output statement into a loop tends to output more than one line.

Related

how to make my code to keep asking to input names from the array until stop is inputed

I need to make my code to keep asking to input flower names(from the options in my array) until "stop" is inputted, keep in mind i am working with a parallel array that also gives me the prices of the flowers. at the end i need a total of all the flowers inputted. thanks for you help.
public static void main(String[] args) {
String[] flowers = {"petunia", "parse", "rose", "violet", "daisy"};
double[] cost = {.50, .75, 1.50, 1.00, .80};
System.out.println("Please enter a name of one flower ex.");
for (String f : flowers) {
System.out.print(f + ",");
}
System.out.println("");
Scanner s1 = new Scanner(System.in);
System.out.print("please enter your flower : ");
String flow;
String stop = "stop";
flow = s1.nextLine();
System.out.println("the flower you chousse si " + flow);
for (int i = 0; i < flowers.length; i++) {
double d = cost[i];
{
if (flow.equalsIgnoreCase(flowers[i])) {
System.out.println("the flowers price " + cost[i]);
}
// else (flow.equalsIgnoreCase(stop)){
System.out.println("your total is ");
}
}
}
// TODO code application logic here
}
}
I think you are expecting something like this.
public static void main(String[] args) {
String[] flowers = { "petunia", "parse", "rose", "violet", "daisy" };
double[] cost = { .50, .75, 1.50, 1.00, .80 };
System.out.println("Please enter a name of one flower ex.");
for (String f : flowers) {
System.out.print(f + ",");
}
System.out.println("\n");
Scanner s1 = new Scanner(System.in);
System.out.print("please enter your flower : ");
String flow = s1.nextLine();
double total = 0.0;
while (!flow.equals("stop")) {
System.out.println("the flower you chousse si " + flow);
for (int i = 0; i < flowers.length; i++) {
{
if (flow.equalsIgnoreCase(flowers[i])) {
System.out.println("the flowers price " + cost[i]);
total += cost[i];
}
}
}
System.out.print("\nplease enter your flower : ");
flow = s1.nextLine();
}
System.out.println("\nyour total is " + total);
}
You can use HashMap key, value pairs, rather than using arrays for these type of scenarios.
If you use Map.of, String.join, Map.containsKey and Map.get you get more concise Java code. Please see below.
public static void main(String[] args) {
var flowers = Map.of("petunia", .50, "parse", .75, "rose", 1.50, "violet", 1.00, "daisy", .80);
System.out.println("Please enter a name of one flower ex.");
System.out.print(String.join(", ", flowers.keySet()));
Scanner s1 = new Scanner(System.in);
double total = 0.0;
String flow;
do {
System.out.print("\nplease enter your flower : ");
flow = s1.nextLine();
var f = flow.toLowerCase();
if (flowers.containsKey(f)) {
var cost = flowers.get(f);
System.out.println("the flowers price " + cost);
total += cost;
}
} while (!flow.equals("stop"));
System.out.println("\nyour total is " + total);
}

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

Need assistance! printing previous user input data from a loop

Hey new guy here need assistance in my problem! i need to print previous user input data from a loop the problem is that it prints the last data the user inputs. Please shed some light my mind is getting dark. I appreciate all of you answers. Thank you!
My program: (Sorry if it's disgusting af)
package activity2;
import java.util.Scanner;
public class Activity2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
for (x=0;x<a;x++){
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sum +=q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
for(int t=0; t<x; t++){
System.out.println(pnum[sum2]+"."+name[sum2]+"---------"+v);
}
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
}
One approach is to use a StringBuilder.
(direct quote below from link)
"StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations."
You can save data with StringBuilder, then print everything all at one time. This makes life a little easier too ;-)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (x=0;x<a;x++) {
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sb.append(pnum[sum2]+"."+name[sum2]+"---------"+q + "\n");
sum +=q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
System.out.println(sb);
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
This will give you the output you're looking for.
The issue is you're not saving each entry. If you want to be able to print it back at the end you need to do this. I'm not exactly sure what you're trying to do, but this should at least give you an idea on what you need to do in order to be able to print out transaction details. Also you really need to name your variables a lot better.
import java.util.Scanner;
public class Activity2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
int[] productNum = new int[a];
String[] products = new String[a];
double[] prices = new double[a];
for (x=0;x<a;x++){
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sum +=q;
productNum[x] = w;
products[x] = name[w];
prices[x] = q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
for(int t=0; t<x; t++){
System.out.println(productNum[t]+"."+products[t]+"---------"+prices[t]);
}
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
}

How do I add user input to parallel arrays in java?

This is the code I have now and it is completely butchered. I am having issues try to allow user input of a String and two doubles to go into 3 parallel arrays and then save to a .txt file. I can not figure out what is wrong could someone please assist me?
public static void addGames(int i, String[] array1, double[] array2,
double[] array3, int arrayLength, Scanner keyboard) throws IOException
{
String newName;
double newPrice;
double newRating;
if(i < arrayLength)
{
System.out.println("Please enter another game name: ");
newName = keyboard.next();
array1[i] = newName;
System.out.println("Please enter another game price: ");
newPrice = keyboard.nextDouble();
array2[i] = newPrice;
System.out.println("Please enter another game rating: ");
newRating = keyboard.nextDouble();
array3[i] = newRating;
i++;
}
else
{
System.out.println("There is no more room to store games: ");
}
PrintWriter gamerOut = new PrintWriter("Project1_VideoGames.txt");
while(i < array1.length)
{
gamerOut.write(array1[i]);
gamerOut.add(array2[i]);
gamerOut.add(array3[i]);
i++;
}
gamerOut.close();
}
for (int j = 0; j < i; ++j) {
gamerOut.println(array1[j] + "\t" + array2[j] + "\t" + array3[j]);
No need to say the names are too imaginative for me. Make a
public class Game {
String name;
double price;
double rating;
}
Check if this is what you want.
Instead of having 3 arrays, I encapsulated all in a Gameclass.
public class Game {
private String name;
private double price;
private double rating;
public Game(String name, double price, double rating){
this.name = name;
this.price = price;
this.rating = rating;
}
#Override
public String toString(){
String ret = "";
ret = ret + name + " / " + price + " / " + rating;
return ret;
}
}
And this is what I came with for your addGames function. It only takes 1 parameter now: the number of games you want to write in the file.
public static void addGames(int gamesNumber) throws IOException
{
int i = 0;
String newName;
double newPrice, newRating;
Scanner keyboard = new Scanner(System.in);
ArrayList<Game> array = new ArrayList<Game>();
while(i < gamesNumber)
{
System.out.println("Please enter another game name: ");
newName = keyboard.next();
System.out.println("Please enter another game price: ");
newPrice = keyboard.nextDouble();
System.out.println("Please enter another game rating: ");
newRating = keyboard.nextDouble();
System.out.println();
Game game = new Game(newName, newPrice, newRating);
array.add(game);
i++;
}
System.out.println("There is no more room to store games. ");
PrintWriter gamerOut = new PrintWriter("Project1_VideoGames.txt");
i = 0;
while(i < array.size())
{
gamerOut.println(array.get(i));
i++;
}
gamerOut.close();
System.out.println("The games have been written in the file");
}
You probably want to handle some errors while reading the users input or handle exceptions from the FileWriter but I'll leave that to you.
Also, I've changed to PrintWriter#println method instead of PrintWriter#write and override the toString method in the Game class. You may want to change the implementation of that too.
Hope this helped.

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