The user should be able to input data of 5 customers with balances. However this piece of code only works for 1. I initially thought of using a for OR a while loop but I think they will create the display message 5 times.
import java.util.Scanner;
public class Assignment {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
Customer c [] = new Customer [5];
Customer hold;
String name; int count = 0;
double totalBalance = 0.0;
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
System.out.println("Search for all customers who have more than $100");
for (int i=0; i<count ; i++){
if (c[i].getBalance()>100)
System.out.println(c[i].getName());
totalBalance += balance;
averageBalance = totalBalance/5;
System.out.println("The average balance is: "+averageBalance);
}
}
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
for(int i=0; i<5; i++){
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
}
So, in the above code the display message prints 5 times but every time it will be for different customers. For e.g.
Enter 1 customer name and balance
John
20.0
Enter 2 customer name and balance
Jim
10.0
and so on.
I hope this helps. If you ask me you should be using java.util.ArrayList or java.util.LinkedList. These classes come with many features out of the box and you need not code much as in the case of arrays.
You are asking is not a coding problem but just a matter of design.
For what you are doing as per design you can follow below process or similar.
Enter comma separated user names in single line.
Read the line and split the names, now you have x customers detail like name read in a single shot.
Now you have names, repeat 1-2 above for every type of detail just need to be entered comma separated. Try to take one type of detail at a time, i.e. one, line one detail like salary of emp or department.
for pseudo code:
private String[] getDetails(BuffferReader reader){
// read a line at a time, using readline function
// using readed line/console input, split it on comma using split() function and return array of values.
}
I am trying to write a code that will exchange between AED,MYR,USD. I got to the following code and I cant fix the error.
It looked like the system.in isn't closing so I wrote the inclose(). But I still get the same results.
My problem might be something else and am not seeing it.
EDIT: this is the current code with changes.
import java.util.Scanner;
public class CurrencyConverter
{
protected static long amount;
static long Namount ;
static int commesion;
static String to;
public static void main( String[] args )
{
CurrencyConverterM MSg=new CurrencyConverterM();
CurrencyConverterM account1 = new CurrencyConverterM( );
String from ;
for(int i=0 ;i<3; i++)
{
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
//in.close();
if ("USD".equals(from)) {
amount=((long) (amount*0.27));
amount=account1.converter(to, amount);
}
else if ("MYR".equals(from)) {
amount=((long) (amount * 1.14));
amount =account1.converter(to, amount);
}
else {
if(mmount >= 900) {
Namount = (amount-50);
commesion =50;
}
else
{
Namount = (amount - 10);
commesion = 10;
}
}
System.out.println(MSg.getMsg());
}
}
}
the output should be as follows.
asking for current currency:
asking to what currency u want it:
asking about the amount.
am converting any amount to AED so I make it the main unit, then converting to the wished unit.
EDIT
public class CurrencyConverterM extends CurrencyConverter
{
long am;
#SuppressWarnings("static-access")
long converter (String to,long amount)
{
if ("MYR".equals(to)) {
am=(super.amount*=0.88);
}
else if ("MYR".equals(to)) {
am=(super.amount*=3.7);
}
return am ;
}
#SuppressWarnings("static-access")
public String getMsg()
{
return ("Thank you. The converted amount is "+(super.amount) + ". We will take" +super.commesion + " commission, and you will get "+ super.Namount);
}
}
before it didn't read the user's input, now its not converting the values.
I tried to print out my vales after each calculation but it looks like that the variable am is not being calculated correctly and its being multiplied by a 0 or divided by one ( the last result is always 0 ) but the amount that is in the main class is not 0 and its not converted to AED as well.
So I am getting this :Thank you. The converted amount is 0.0 1000.0. We will take50 commission, and you will get 0.0
String comparison is wrong.
from=="MYR" should be from.equals("MYR") rather I would recommend equalsIgnoreCase which is not case sensitive.
You should call scanner.nextLine() (in.nextLine()) and not in.toString()
Also you can use the same scanner and not to create 3 different scanners.
See the following part of your code updated with one Scanner (in):
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
System.out.println(from + " " + to);
in.close();
by doing in.nextLine() you read the next line of user input.
From java 8 javadocs:
nextLine
public String nextLine()
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
The above will solve the issue that no input is read by your code.
Later you will have issues comparing the String user entered:
from=="USD" should be changed to "USD".equals(from)
Tip: Prefer to use "String".equals(variable) to avoid null pointer exceptions when variable is null.
I am inputting the following things:
book
12.46
music cd
For some reason, the prompt for cost comes up and the next output line comes on the same line. Could someone help me to spot my mistake?
public class SalesTax {
public static void main(String[] args) {
// Input items for shopping cart
HashMap<String, String> cart = new HashMap<String, String>();
// Create a Scanner
Scanner input = new Scanner(System.in);
// variables
char done;
boolean goods;
double tax;
// Pick items for list.
do {
System.out.print("Please enter an item.");
String item = input.next();
System.out.print("Please enter the price for "+ item + ": ");
String price = input.next();
if (item.contains("book")) {
goods = false;
} else if(item.contains("chocolate")) {
goods = false;
} else if(item.contains("pill")) {
goods = false;
}
cart.put(item, price);
System.out.print("Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.");
done = input.next().charAt(0);
} while(Character.toUpperCase(done) == 'Y');
}
}
problem:
String item = input.next();
By the time you input music cd it will consume music by item and price will consume the cd thus skipping it.
solution:
you need to call input.nextLine(); to consume the whole line of string
By default, next() just gets input upto a whitespace so you'd have to use nextLine() instead, which will read in the whole line of input upto a carriage return.
use input.nextLine() to read an entire line from the keyboard. Means what ever the user typed till the user presses the enter key.
One thing that I did not understand is, what is the use of having this in your code
if(item.contains("book"))
{
goods = false;
}
else if(item.contains("chocolate"))
{
goods = false;
}
else if(item.contains("pill"))
{
goods = false;
}
???
Can you please explain?
Thanks,
you are using System.out.print() instead use System.out.println();
print() will just print the word and stays on the same line.
println() will print the whole line and cursor goes to second line .
And don't use the spaces while reading as you are writing it as
input.next();
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
edit:
just change the declaration to this.
Scanner s = new Scanner(input).useDelimiter("\n");
It will change the delimiter to new line and read the complete line.
I'm stuck and need your help (yes, it's homework), what I'm trying to do is get my code to read the contents in the text file and output the words by specific words. For example I want it to output all words that start with letter "g".
Here's a pseudocode code if I didn't explain that well:
BEGIN
Get the initial letter from the user
While there are more entries in the file
Get the next personal name
Get the next surname
Get the next year info
If the surname starts with the initial letter
Output the person name, surname and year info
End while
END
So far I've managed to get this done, and now I'm stuck where you output the names correctly. Any help or tutorials will be appreciated.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PrimeMinisters
{
public static void main(String[] args) throws FileNotFoundException
{
// ask the user for the first letter
Scanner keyboard = new Scanner(System.in);
System.out.print("What is the first letter? ");
String input = keyboard.next().toLowerCase();
char firstLetter = input.charAt(0);
// open the data file
File pmFile = new File ("OZPMS.txt");
// create a scanner from the file
Scanner pmInput = new Scanner (pmFile);
// read one line of data at a time, processing each line
while(pmInput.hasNext())
{
String names = pmInput.next();
System.out.println(names);
}
// be polite and close the file
pmInput.close();
}
}
I'd recommend using nextLine() over next(). From this you would then use the String's startsWith(String stringsequence) method which returns a boolean to get all the values beginning with the letter of your choice:
while(pmInput.hasNextLine())
{
String names = pmInput.nextLine();
System.out.println(names);
if(names.startsWith("g")) {
//the name begins with letter g do whatever
}
}
You can have a look at more methods for String here: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Since your requirements state to look at the surname's first letter, it will be easier to tokenize each line while you read it (while checking to see if the user input is the first letter of the surname). Assuming that the line is in the order that you stated above, the surname will be token #2 (index 1 of the array).
public class PrimeMinisters
{
public static void main(String[] args) throws FileNotFoundException
{
// ask the user for the first letter
Scanner keyboard = new Scanner(System.in);
System.out.print("What is the first letter? ");
String input = keyboard.next().toLowerCase();
char firstLetter = input.charAt(0);
// open the data file
File pmFile = new File ("OZPMS.txt");
// create a scanner from the file
Scanner pmInput = new Scanner (pmFile);
// read one line of data at a time, processing each line
while(pmInput.hasNextLine())
{
String names = pmInput.nextLine();
// Break line into tokens. This is assuming that there are only
// 3 strings per line in the following order (personal name, surname, yearinfo)
//
String[] info = names.split("\\s");
// Check 2nd string in line (since you are looking for the first character in
// the surname and not the personal name.
//
if(info[1].startsWith(input))
{
System.out.println(info[0] + "\t" + info[1] + "\t" + info[2]);
}
}
// be polite and close the file
pmInput.close();
}
}
One of the homework assignments my instructor gave me was a baseball statistics program. It reads from a file called stats.dat, which contains the name of a baseball player's name and a list of what happened when they were at the bat. It reads and prints their name and the amount of outs(o), hits(h), walks(w), and sacrifice flies(s) that they have. This is what the file contains:
Willy Wonk,o,o,h,o,o,o,o,h,w,o,o,o,o,s,h,o,h
Shari Jones,h,o,o,s,s,h,o,o,o,h,o,o,o
Barry Bands,h,h,w,o,o,o,w,h,o,o,h,h,o,o,w,w,w,h,o,o
Sally Slugger,o,h,h,o,o,h,h,w
Missy Lots,o,o,s,o,o,w,o,o,o
Joe Jones,o,h,o,o,o,o,h,h,o,o,o,o,w,o,o,o,h,o,h,h
Larry Loop,w,s,o,o,o,h,o,o,h,s,o,o,o,h,h
Sarah Swift,o,o,o,o,h,h,w,o,o,o
Bill Bird,h,o,h,o,h,w,o,o,o,h,s,s,h,o,o,o,o,o,o
Don Daring,o,o,h,h,o,o,h,o,h,o,o,o,o,o,o,h
Jill Jet,o,s,s,h,o,o,h,h,o,o,o,h,o,h,w,o,o,h,h,o
So far I have the basic idea down, even though I don't quite understand what each line is doing(I modified some code of a program in the book my class is reading that prints a URL that's in a text file and then prints out each part of the url that's separated by a /). I have it so that the program prints out the player's name, but I'm stumped on how to print out the amount of hits, outs, walks, and sacrifice flies they get. So far it's reading 1 character out of the line, then it goes down to the next player and prints out 2, then 3, etc. Here's the code I have for it so far:
import java.util.Scanner;
import java.io.*;
public class BaseballStats
{
public static void main(String [] args) throws IOException
{
int hit = 0, walk = 0, sac = 0, out = 0, length = 0, wholeLength = 0;
Scanner fileScan, lineScan, statScan;
String fileName, playerName, line, stats, playerStats;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the name of the file: ");
fileName = scan.nextLine();
fileScan = new Scanner(new File(fileName));
while (fileScan.hasNext())
{
System.out.println();
line = ("Player: " + fileScan.nextLine());
wholeLength = line.length();
lineScan = new Scanner(line);
lineScan.useDelimiter(",");
stats = lineScan.next();
statScan = new Scanner(stats);
statScan.useDelimiter(",");
while (statScan.hasNext())
{
System.out.println(statScan.next());
length = stats.length() - 1;
for (int i = 0; i < length; i++)
{
if (stats.charAt(i) == 'h')
hit++;
else if (stats.charAt(i) == 'o')
out++;
else if (stats.charAt(i) == 'w')
walk++;
else if (stats.charAt(i) == 's')
sac++;
}
}
System.out.println("Hits: " + hit + "\nOuts: " + out + "\nWalks: " + walk + "\nSacrifice flies: " + sac);
}
}
}
(I'm having a hard time getting the last part of the last statement in my code to appear correctly in the editor, sorry if it looks a bit weird) I have been wondering what's wrong and I can't figure it out so far. Is there anything to get me on the right track?
If looks like you're creating one Scanner instance too many:
You use the first Scanner: fileScan to read one line at a time and assign this to line.
You then create a Scanner: lineScan to read over the line one field at a time.
However, you only read the first token from lineScan and then create a third Scanner instance: statsScan. Rather than do this, you simply need to read all the tokens from lineScan, storing the first as the person's name and processing the subsequent tokens as statistics.
One other thing I'd advise is to create a dedicated class to hold the person's name and statistics and implement toString() on this class to produce a sensible String representation; e.g.
public class Player {
private final String name;
private int hit, out, walk, sac;
public int getNumHits() {
return hit;
}
public int incrementNumHits() {
return ++hit;
}
// TODO: Implement other getter and increment methods.
public String toString() {
return String.format("%s. Hits: %d, Outs: %d, Walks: %d, Sacrifice flies: %d",
name, hit, out, walk, sac);
}
}
By implementing toString() you simply need to create and populate your Player class with statistics and then print it out; e.g.
Player player = new Player("Jim");
player.incrementNumHits();
// etc.
System.out.println(player);