I want to show my initials in a code. For example, if my name is Donald Trump, the program shall write D.T.
How do I do this the easiest way?
package pack_prov;
import javax.swing.*;
public class Filip_Degeryd_uppgift_3 {
public static void main(String[] args) {
String f;
String e;
f = JOptionPane.showInputDialog("first name ");
e = JOptionPane.showInputDialog("last name ");
JOptionPane.showMessageDialog(null, "initials " + f + e + "is" +
f.charAt(0) + ".") + e.charAt(0);
}
}
Here:
public class Test {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter First Name:");
String frstNme = scn.nextLine();
System.out.println("Enter Last Name:");
String lstNme = scn.nextLine();
System.out.println("Your Name Initial Is: " + frstNme.substring(0, 1) + "." + lstNme.substring(0, 1) + ".");
scn.close();
}
}
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 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.
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;
}
}
I have an assignment where the user is asked for baby name using a scanner. Then it reads through files names.txt and meanings.txt and returns the popularity of the name for each decade ranging from 1890 - 2010 then it prints out the meaning. Some names have multiple meanings and some are used in both genders. The assignment states to print only the first line where the name is found. I am having trouble only returning the first line in which the name is found. PLEASE HELP ME!
import java.io.*;
import java.util.*;
public class BabyNames4 {
public static void main(String[] args) throws FileNotFoundException {
printIntro();
Scanner console = new Scanner(System.in);
System.out.print("Name: ");
String searchWord = console.next();
Scanner fileScan = new Scanner(new File("names.txt"));
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan);
}
}
Scanner fileScan2 = new Scanner(new File("meanings.txt"));
String dataLine2 = find(searchWord, fileScan2);
if (dataLine2.length() > 0) {
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
}
}
public static void printIntro() {
System.out.println("This program allows you to search through the");
System.out.println("dada from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since 1890");
System.out.println();
}
public static String find(String searchWord, Scanner fileScan) {
while (fileScan.hasNextLine()) {
String dataLine = fileScan.nextLine();
String dataLineLC = dataLine.toLowerCase();
if (dataLineLC.contains(searchWord.toLowerCase())) {
return dataLine;
//} else { runs a continuous loop
//System.out.println(search" not found.");
}
}
return "";
}
public static void printName(String dataLine) {
Scanner lineScan = new Scanner(dataLine);
String name = lineScan.next();
String gender = lineScan.next();
String rank = "";
while (lineScan.hasNext()) {
rank += lineScan.next() + " ";
}
System.out.println(name + (" ") + gender + (" ") + rank);
}
public static void printMeaning(String dataLine2) {
Scanner lineScan2 = new Scanner(dataLine2);
String name2 = lineScan2.next();
String gender2 = lineScan2.next();
String language = lineScan2.next();
String meaning = "";
while (lineScan2.hasNext()) {
meaning += lineScan2.next() + " ";
}
System.out.println(name2 + (" ") + gender2 + (" ") + language + (" ") + meaning);
}
}
It looks like sushain hit it with his comment.
The loop:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
dataLine2 = find(searchWord, fileScan2);
}
could be changed to:
while (dataLine2.length() > 0) {
printMeaning(dataLine2);
break;
}
This way you do not find the second definition and do not print it.
In this loop, you don't need to find the next line, correct?
if (dataLine.length() > 0) {
while (dataLine.length() > 0) {
printName(dataLine);
dataLine = find(searchWord, fileScan); // remove this line
}
}
If you remove the next find to dataLine and remove the while blocks in both instances where you search the file, you won't need a break, and you'll only end up printing one instance.
Do this:
String dataLine = find(searchWord, fileScan);
if (dataLine.length() > 0) {
printName(dataLine);
}
this code is to be used to write the data inserted in to a file
when the loop runs the second student dont get entered i dont know why
this keeps getting stuck at the second student and i have been working on this for hours
import java.util.Scanner;
import java.io.*;
class wonder
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(System.in);
FileWriter ww = new FileWriter("D:\\student details.txt");
BufferedWriter o = new BufferedWriter(ww);
int counter = 0 ;
int stnum = 1;
while(counter < 4)
{
String name = "";
int marks = 0;
System.out.print("Enter student " + stnum + " name : " );
name = c.nextLine();
System.out.print("Enter marks : ");
marks = c.nextInt();
ww.write(stnum + " " + name + " " + marks );
ww.close();
counter++;
stnum++;
}
}
}
You close your FileWriter in each iteration of your while loop... what did you think would happen?
you close the writer in the loop, move the close statement outside of the loop
ww.close();
Things to do
put ww.close(); outside the while loop
change c.nextLine(); to c.next();
import java.util.Scanner;
import java.io.*;
class wonder
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(System.in);
FileWriter ww = new FileWriter("D:\\student details.txt");
BufferedWriter o = new BufferedWriter(ww);
int counter = 0 ;
int stnum = 1;
while(counter < 4)
{
String name = "";
int marks = 0;
System.out.print("Enter student " + stnum + " name : " );
name = c.next();
System.out.print("Enter marks : ");
marks = c.nextInt();
ww.write(stnum + " " + name + " " + marks );
counter++;
stnum++;
}
ww.close();
}
}