I have this code in Java,
package bookpurchased;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Book {
public static void getInputFromScanner() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the Number you want: ");
Short bookId = input.nextShort();
System.out.println("\nBook Price : ");
double bookPrice = input.nextDouble();
System.out.println("The Book Category is: " + bookId);
System.out.println("The Book Price is: " + bookPrice);
input.close();
}
public static void getInputFromReader() {
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String bookTitle = "";
System.out.print("Enter book title");
here below it:
I want to change the bookCategory from String to char, but if I change, I have received a lots of error. It's like a string when in run but I have to change only a bookCategory from String to char.
String bookCategory = "";
System.out.print("Enter book title");
try {
bookTitle = dataIn.readLine();
bookCategory = dataIn.readLine();
}catch(IOException e) {
System.out.println("Error!");
}
System.out.println("The book title is: " + bookTitle);
System.out.println("The book category is: " + bookCategory);
}
public static void main(String[]args) {
getInputFromReader();
getInputFromScanner();
}
}
You can make of String.toCharArray() i.e., bookCategory.toCharArray() or dataIn.readLine().toCharArray() will give you char[] array.
But you have to intialize the bookCategory to char array or you can print directly the converted char[] array using Arrays.toString()
Related
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
i have problem with my program << this program take information for 3 student name and id and marks in 5 course then return information with marks avrage my program is work good but it return same avrage for all student its same number please can u help me
this is the class
StudentsMarks.java
package programmersx;
import java.io.BufferedWriter;
import java.io.*;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StudentsMarks {
private String studentName;
private int studentId;
private double marks[];
public static int NoInstntitd;
public StudentsMarks() {
NoInstntitd += 1;
}
double avgCalculator(double[] marks) { //avg method
double sum =0;
double avg=0;
for (int i = 0; i < marks.length; i++) {
sum = sum + marks[i];
avg=sum/5;
}
return avg;
}
#Override
public String toString() {
return studentName +" " + studentId +" " + Arrays.toString(marks) +" " ;
}
void toFile(String fileName) throws IOException {
FileOutputStream file= new FileOutputStream(fileName);
PrintWriter writer= new PrintWriter(file);
writer.print("reem ");
String information = "student information :" + getStudentName() + "" + getStudentId() + " average " + avgCalculator(marks);
LocalDate localDate = LocalDate.now();
BufferedWriter writer1 = new BufferedWriter(new FileWriter("average.txt"));
BufferedWriter writer2 = new BufferedWriter(new FileWriter("localDate.txt"));
try {
writer.write(information);
writer1.write(" average " + avgCalculator(marks));
writer2.write(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
writer2.close();
} catch (IOException ex) {
Logger.getLogger(Programmersx.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("student information :" + getStudentName() + "" + getStudentId() + " average " + avgCalculator(marks));
System.out.println(" student average. : " + avgCalculator(marks));
System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
}
{
NoInstntitd += 1;
}
void display( ) {
System.out.println("display the count of the instantiated objects from StudentMarks" + getNoInstntitd());
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public double[] getMarks() {
return marks;
}
public void setMarks(double[] marks) {
this.marks = marks;
}
public int getNoInstntitd() {
return NoInstntitd;
}
public void setNoInstntitd(int NoInstntitd) {
this.NoInstntitd = this.NoInstntitd + 1;
}
}
this is main
Programmersx.java
package programmersx;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Programmersx {
public static void main(String[] args) throws IOException {
StudentsMarks myObject = new StudentsMarks();
StudentsMarks myObject1 = new StudentsMarks();
StudentsMarks myObject2 = new StudentsMarks();
System.out.print("Please enter your student Name : ");
Scanner myObj = new Scanner(System.in); // Create a Scanner object
myObject.setStudentName(myObj.next()) ;
System.out.print("Please enter your student Id : ");
myObject.setStudentId(myObj.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks[] = new double [5];
for (int i = 0; i < 5; i++) {
marks[i]= myObj.nextInt();
}
myObject.setMarks(marks) ;
System.out.print("Please enter your student Name : ");
Scanner myObj1 = new Scanner(System.in); // Create a Scanner object
myObject1.setStudentName(myObj1.next()) ;
System.out.print("Please enter your student Id : ");
myObject1.setStudentId(myObj1.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks1[] = new double [5];
for (int i = 0; i < 5; i++) {
marks1[i]= myObj1.nextInt();
}
myObject1.setMarks(marks) ;
myObject1.toString();
System.out.print("Please enter your student Name : ");
Scanner myObj2 = new Scanner(System.in); // Create a Scanner object
myObject2.setStudentName(myObj2.next()) ;
System.out.print("Please enter your student Id : ");
myObject2.setStudentId(myObj2.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks2[] = new double [5];
for (int i = 0; i < 5; i++) {
marks2[i]= myObj2.nextInt();
}
myObject2.setMarks(marks) ;
myObject2.toString();
myObject.toString();
myObject.toFile("Reem.txt");
myObject1.toFile("MAria.txt");
myObject2.toFile("Abrar.txt");
System.out.println("display the count of the instantiated objects from StudentMarks: " + StudentsMarks.NoInstntitd );
}
}
the output is
run:
Please enter your student Name : jack
Please enter your student Id : 1123
Please enter your marks of 5 courses :
6
4
5
7
6
Please enter your student Name : mick
Please enter your student Id : 87534
Please enter your marks of 5 courses :
6
4
3
22
5
Please enter your student Name : meno
Please enter your student Id : 43433
Please enter your marks of 5 courses :
6
55
33
22
7
student information :jack1123 average 5.6
student average. : 5.6
2019/12/06
student information :mick87534 average 5.6
student average. : 5.6
2019/12/06
student information :meno43433 average 5.6
student average. : 5.6
2019/12/06
display the count of the instantiated objects from StudentMarks: 6
All of the StudentMarks objects have their marks set by a similar call:
myObject2.setMarks(marks)
They all use the same marks array, so they all have the same marks.
Even if you change the content of the marks array between
myObject.setMarks(marks)
and
myObject1.setMarks(marks)
there's still only one marks array, shared by all StudentMarks objects: the StudentMarks setter does not copy the array.
All student are setted the same marks
myObject.setMarks(marks)
myObject1.setMarks(marks)
myObject2.setMarks(marks)
You should change your code like this
myObject.setMarks(marks)
myObject1.setMarks(marks1)
myObject2.setMarks(marks2)
This is my code:
import java.util.*;
import java.util.Arrays;
public class PhoneNumbers
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
String phoneList[][] =
{
{"Harrison, Rose: ", "James, Jean: ", "Smith, William: ", "Smith, Brad: "},
{"415-555-2234", "415-555-9098", "415-555-1785", "415-555-9224"}
};
System.out.println(Arrays.deepToString(phoneList)); //this line is to make sure the 2D arrays work
String input;
System.out.print("Enter the first few letters of a last name to search for: ");
input = scan.nextLine();
int match = -1;
for(int i = 0; i < phoneList.length; i++)
{
if(phoneList[i].indexOf(input))
{
System.out.println(phoneList[i]);
match = i;
break;
}
else
System.out.println("There is no match.");
}
}
}
My goal is:
I have a 2D array, i got name in one and the phone number in another.
I am trying to allow user to enter first few letters of a last name and do a search that and display the matching search along with the phone number(this would be my next challenge).
Thank you,
Here is your Answer :
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int refNumber=-1;
String phoneList[][] =
{
{"Harrison, Rose: ", "James, Jean: ", "Smith, William: ", "Smith, Brad: "},
{"415-555-2234", "415-555-9098", "415-555-1785", "415-555-9224"}
};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter String to be searched ->");
String input = scanner.nextLine();
//System.out.println(input);
for (int i=0; i<phoneList[0].length; i++) {
if (phoneList[0][i].contains(input)) {
refNumber = i;
}
}
System.out.println("Name ->"+phoneList[0][refNumber]);
System.out.println("Phone No ->"+phoneList[1][refNumber]);
}
}
Create a dictionary (e.g. trie tree) for all the names you have. While creating/updating your search dictionary, at each node, keep an integer array which gives you the list of index of all the matching names. As the user provides input, you can keep on refining the result at runtime, and when he selects any one of the provided suggestions, you'll have the index to it.
Rest is simple, using that index, display the phone number of the selected person.
I did some refactoring:
using a Map: name => phone
public static void main(String[] args)
{
String phoneList[][] =
{
{"Harrison, Rose: ", "James, Jean: ", "Smith, William: ", "Smith, Brad: "},
{"415-555-2234", "415-555-9098", "415-555-1785", "415-555-9224"}
};
// Make a Map
Map<String,String> mss=new HashMap<String,String>();
for(int i = 0; i < phoneList.length; i++)
mss.put(phoneList[0][i], phoneList[1][i]) ;
String input;
System.out.print("Enter the first few letters of a last name to search for: ");
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
String match="";
for (String name: mss.keySet())
if (name.startsWith(input))
{
System.out.println("NAME:"+name+ " PHONE:"+mss.get(name));
match=name;
break;
}
if (match.equals(""))
System.out.println("There is no match.");
}
One simple approach is to match the beginning of the input String:
for(int x=0; x<phoneList[1].length; x++)
if(phoneList[0][x].toLowerCase().startsWith(input.toLowerCase()))
System.out.println("Numbers which matched: " + phoneList[1][x]);
Program output:
//Using "smith" as input:
Numbers which matched: 415-555-1785
Numbers which matched: 415-555-9224
I am creating an array using a while loop. (For reasons why I am creating an array this way, go to https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt) Though once my array (data) is created inside the while loop, I cannot access it outside of the while loop. I was hoping to make it so the user could put in the name of a country, say India, and get the number of mobile users in that country.
String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
while (in1.hasNextLine()){
line = in1.nextLine();
String[] data = line.split("\t");
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
}
else{
System.out.println("No country found with that name!");
return;
}
}
The input works if it is inside the loop, but will only work with China because it is the first country in the list. I understand why it is not working correctly, thought I'm unsure how to fix it other than putting the if statement outside of the loop, but if I do that, the statement cannot reach my array. Any suggestions?
The issue is here :
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
} else {
System.out.println("No country found with that name!");
return; //<-----ISSUE
}
When return is called in your else clause it terminates the program. What it really needs to do is iterate through the second run of the loop.
Remove the return in your else-statment.
Here's the revised code:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) throws IOException {
String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out
.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
while (in1.hasNextLine()) {
line = in1.nextLine();
String[] data = line.split("\t");
if (data[1].contains(country) == true) {
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return; //<--- will exit after printing ^
}
}
System.out.println("No country found with that name!");
}
}
Here's a sample run: {input} India
Please enter the name of the country you would like to see the mobile users for: India
Country name: India
Mobile phone subscribers: 893,862,000
You are not able to iterate to second line because you are returning the while after first iteration whether it found the country or not.
I would suggest to remove the return statement from the else condition.
I have also used a boolean variable found which will be set once the country is found and No country found message will be appear only if that country is not in list.
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
boolean found = false;
String line;
System.out
.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
while (in1.hasNextLine()) {
line = in1.nextLine();
final String[] data = line.split("\t");
if (data[1].contains(country) == true) {
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
found = true;
return;
}
}
if (!found) {
System.out.println("No Country Found");
}
in.close();
in1.close();
}
}
On the other note, if you wants to use collections your program will become more concise and easy to read. Here is the same logic with HashMap
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
final Map<String, String> countryMap = new HashMap<String, String>();
while (in1.hasNextLine()) {
final String[] line = in1.nextLine().split("\t");
countryMap.put(line[1], line[2]);
}
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
if (countryMap.containsKey(country)) {
System.out.println("Country Name: " + country);
System.out.println("Mobile phone subscribers: "+ countryMap.get(country));
} else {
System.out.println("No Country found with that name");
}
in.close();
in1.close();
}
}
Try putting
String[] data;
before your loop. That will make its scope greater than just the loop.
Declare data outside "while" but assign it inside.
String address = "https://www.cia.gov/library/publications/the-world- factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
String[] data;
while (in1.hasNextLine()){
line = in1.nextLine();
data = line.split("\t");
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
} else{
System.out.println("No country found with that name!");
return;
}
}
Objects.toString(data); // now its visible
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.