Java string not showing when run [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I can't seem to figure out why the string college doesn't show when I run this. There are no errors when I compile it. What am I doing wrong? Everything else is working. It's probably an easy fix, but I'm new and just starting to learn Java.
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String college;
String profession;
String animal;
String petname;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}

Call keyboard.nextLine() after age = keyboard.nextInt();.
Currently int value is read as age and college = keyboard.nextLine(); reads the remainder of the line which container your int, which is empty. So the correct form should be:
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
Other possible solution to avoid the extra call to nextLine() is reading the whole line as a String and then parsing that String to an integer, for example:
age = Integer.parseInt(keyboard.nextLine());

Put keyboard.nextLine() after this line:
int age=keyboard.nextInt();
This is a common problem that usually happens when you use nextLine() method after nextInt() method of Scanner class.
What actually happens is that when the user enters an integer at int age = keyboard.nextInt();, the scanner will take the digits only and leave the new-line character \n. So you need to do a trick by calling keyboard.nextLine(); just to discard that new-line character and then you can call String college = keyboard.nextLine(); without any problem.
this is taken from Reading Strings next() and nextLine() Java

The problem with your code is using nextLine() after nextInt() & you have an additional nextLine()
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine(); --> this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
What you should do is :
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine(); -->add this line
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// keyboard.nextLine(); --> remove this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
A better way of doing it would be : (read about Integer.pasrseInt(String))
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());

import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String profession;
String animal;
String petname;
String college;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println(college);
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}

Related

Why doesn't my program return the file line I searched for inside a txt file?

Hi this has me stumped I'm trying to search my file for a selected number and then display that number with the rest of the line, the problem is that my program seems to return the first line of contents when I search for it, but not second or third lines when I type in to search for them
public static String searchProject(String searchTerm, String filepath) {
String findString = "";
boolean found = false;
String projectNumber = "";
String projectName = "";
String typeProject = "";
String address = "";
String erf = "";
String fee = "";
String paid = "";
String deadline = "";
String finalised = "";
String architectName = "";
String architectTel = "";
String architectEmail = "";
String architectAddress = "";
String contractorName = "";
String contractorTel = "";
String contractorEmail = "";
String contractorAddress = "";
String customerName = "";
String customerTel = "";
String customerEmail = "";
String customerAddress = "";
try {
Scanner userInput = new Scanner(System.in);
userInput = new Scanner(new File(filepath));
userInput.useDelimiter("[,\n]");
while (userInput.hasNext() && !found) {
projectNumber = userInput.next();
projectName = userInput.next();
typeProject = userInput.next();
address = userInput.next();
erf = userInput.next();
fee = userInput.next();
paid = userInput.next();
deadline = userInput.next();
finalised = userInput.next();
architectName = userInput.next();
architectTel = userInput.next();
architectEmail = userInput.next();
architectAddress = userInput.next();
contractorName = userInput.next();
contractorTel = userInput.next();
contractorEmail = userInput.next();
contractorAddress = userInput.next();
customerName = userInput.next();
customerTel = userInput.next();
customerEmail = userInput.next();
customerAddress = userInput.next();
if (projectNumber.equals(searchTerm)) {
findString = "\nProject Number: " + projectNumber + "\nProject Name: " + projectName + "\nType Project: " + typeProject + "\nAddress: "
+ address + "\nERF number: " + erf + "\nTotal fee: R" + fee + "\nPaid to date: R" + paid + "\nProject Deadline: "
+ deadline + "\nIs the project finalised: " + finalised + "\nArchitect Name: " + architectName + "\nArchitect Telephone: " + architectTel + "\nArchitect Email: "
+ architectEmail + "\nArchitect Address: " + architectAddress + "\nContractor Name: " + contractorName + "\nContractor Telephone: " + contractorTel + "\nContractor Email: "
+ contractorEmail + "\nContractor Address: " + contractorAddress + "\nCustomer Name: " + customerName + "\nCustomer Telephone: " + customerTel + "\nCustomer Email: "
+ customerEmail + "\nCustomer Address: " + customerAddress;
System.out.println(findString);
}
}
} catch (Exception e) {
}
return findString;
}
my txt file contents
1,House mack,house,123 mack road,155,100000,40000,2022-09-14,no,Bill,123456,bill#gmail.com,12 Bill road,Jack,456789,jack#gmail.com,23 Jack road,John,789632,john#gmail.com,34 John road,
2,House John,house,123 John road,183,160000,50000,2022-09-10,yes,Bill,123456,bill#gmail.com,12 Bill road,Jack,456789,jack#gmail.com,23 Jack road,John,789632,john#gmail.com,34 John road,
3,House bill,house,123 bill road,193,160000,50000,2022-09-10,yes,Bill,123456,bill#gmail.com,12 Bill road,Jack,456789,jack#gmail.com,23 Jack road,John,789632,john#gmail.com,34 John road,
the output I am looking for
Please enter the project number to find the task: 1
Project Number: 1
Project Name: House mack
Type Project: house
Address: 123 mack road
ERF number: 155
Total fee: R100000
Paid to date: R40000
Project Deadline: 2022-09-14
Is the project finalised: no
Architect Name: Bill
Architect Telephone: 123456
Architect Email: bill#gmail.com
Architect Address: 12 Bill road
Contractor Name: Jack
Contractor Telephone: 456789
Contractor Email: jack#gmail.com
Contractor Address: 23 Jack road
Customer Name: John
Customer Telephone: 789632
Customer Email: john#gmail.com
Customer Address: 34 John road
when I type in 2 or 3 to find the project my program displays nothing where is the problem and how can I fix it?
The problem is that your text file contains one column more than your parsing code expects (it contains a , after the last data field which makes it a total of 22 columns of which you read only 21).
Due to this mismatch, the reading of the "second" project starts with the empty last field of the first line instead of the project number in the second line.
To check this you could write out the projectNumber just after you have read it:
projectNumber = userInput.next();
System.out.println("projectNumber=" + projectNumber);
One way to fix this would be to add an extra userInput.nextLine(); after you have read all the fields of a row:
customerAddress = userInput.next();
userInput.nextLine();
But IMHO it would be better to rewrite your code to read line by line and split each line separately into the columns. By reading the whole file as a sequence of columns you ignore the structure that your data has - and that structure could help you find mistakes in the data and / or in the code.
Additional note: why do you create a new Scanner(System.in); if you never use it? I'm talking about those two lines:
Scanner userInput = new Scanner(System.in);
userInput = new Scanner(new File(filepath));
You should replace those two lines with a single line
Scanner userInput = new Scanner(new File(filepath));

Unreachable Statement After For Loop with If Statement

I have an assignment that is very basic but it's all-new ground for me still. The program is supposed to ask the user(s) to enter their name, surname, grade, and subject. If the subject is not IT their input gets set aside. However, if the subject entered is IT their name, surname and grade will be used later on again to display a message that looks as followed:
DisplayedMessage
The information can differ depending on what the user(s) entered. Now the question comes in. I typed the code correctly but at the end where I display the message using JOptionPane it showed an error saying: "Unreachable Statement". (To clarify it happened next to the line of code) It was strange because it was almost identical to the memo of the assignment yet it had the error. It might have been the Netbeans being confused in a way but I redid the assignment at home and it worked as it should seen here:
String name, surname, subject, message = "IT Learners:\n\n";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter Your "
+ "Grade Here: "));
if (subject.equalsIgnoreCase("IT")) {
message += name + " " + surname + " is in grade "
+ grade + ".\n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");
The next section of code is a copy of the code I wrote on the terminal during the period. I personally can't see the error and I came here to ask is it correct or is there a small error that I just can't seem to find.
Code I did at school:
String name, surname, subject, message = "IT Learners:\n\n";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog
("Enter Your Grade Here: "));
if (subject.equalsIgnoreCase("IT"))
{
message += name + " " + surname + " is in grade "
+ grade + ".\n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");
It truly looks identical, was it just the Netbeans being confused or is there just a fine detail I am missing?
Entire code:
import javax.swing.JOptionPane;
/**
*
* #author (My Name)
*/
public class ITLearners {
public static void main(String[] args) {
// TODO code application logic here
String name, surname, subject, message = "IT Learners:\n\n";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter Your "
+ "Grade Here: "));
if (subject.equalsIgnoreCase("IT")) {
message += name + " " + surname + " " + " is in grade "
+ grade + ".\n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");
}
}
I feel quite silly right now. The problem in the code done at school was that an i in the for loop condition was a 1. Like this:
for ( int i = 0; 1 < 3; i++; )
Lesson learned out of this: make sure you type everything correctly. With the 1 there I created an unintentionally infinite loop without realizing it. Thank you so much for the help, especially #AcidResin!

Can i take userinput in a method java class?

public static void userinput() {
System.out.print("Enter your name : ");
Scanner d = new Scanner(System.in);
String username = d.next();
System.out.print("\nEnter your Age : ");
Scanner a = new Scanner(System.in);
int Age = a.nextInt();
System.out.print("\nEnter your roll number : ");
Scanner b = new Scanner(System.in);
int rollno = b.nextInt();
System.out.print("\nEnter your city : ");
Scanner c = new Scanner(System.in);
String city = c.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
return (0);
}
Is this the correct way to take input from a user in the method?
Here is the corrected version :
public static void userinput() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name : ");
String username = sanner.nextLine();//as next() reads only a word
System.out.print("\nEnter your Age : ");
int age = Integer.parseInt(scanner.nextLine());//as nextInt() does not read the \n which may cause next string inputs to be null
System.out.print("\nEnter your roll number : ");
int rollno = Integer.parseInt(scanner.nextLine());
System.out.print("\nEnter your city : ");
String city = scanner.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
//a void function doesn't compulsorily need a return statement
}
Also only one Scanner is enough!

Printwriter output not accepting .printf formatters to file?

When outputting to an already established file using the following code:
import java.util.Scanner;
import java.io.*;
public class BarakProductOrder
{
public static void main(String[] args) throws IOException
{
//Establish scanner object
Scanner input = new Scanner (System.in);
//Declare variables
String name, product, street, city, state, zip;
int qty;
double price;
//Collect data
System.out.println("Welcome to Matt's Dog Food Emporium!\n\nWhat is your name?");
name = input.nextLine();
System.out.println("Which product would you like to order today?");
product = input.nextLine();
System.out.println("How many would you like?");
qty = input.nextInt();
price = 4.56*qty;
input.nextLine(); //Must be placed to not skip over "address" line
System.out.println("Enter your street address:");
street = input.nextLine();
System.out.println("Enter the City:");
city = input.nextLine();
System.out.println("Enter the State (ex.: NY):");
state = input.nextLine();
System.out.println("Enter the Zip:");
zip = input.nextLine();
System.out.println("Thank you for your order, " + name);
//Output data to file "BarakOrder.txt"
PrintWriter outputFile = new PrintWriter("C:\\Users\\fbara\\Desktop\\CISS 110\\BarakOrder.txt");
outputFile.println("Order Number: 001");
outputFile.println("Product: " + product);
outputFile.println("Quantity: " + qty);
outputFile.printf("Price = 4.56*" + qty + " = $" + "%.2f" + price);
outputFile.println("Customer Contact Info: " + name);
outputFile.println("Address: " + street);
outputFile.println(city + ", " + state + " " + zip);
//Close scanner and file object
input.close();
outputFile.close();
System.out.println("Data has been written.");
}
}
Using the "%.2f" modifier at line 45 gives me the following error message:
java.util.MissingFormatArgumentException: Format specifier '%.2f' at
java.util.Formatter.format(Unknown Source) at
java.io.PrintWriter.format(Unknown Source) at
java.io.PrintWriter.printf(Unknown Source) at
BarakProductOrder.main(BarakProductOrder.java:45) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
Am I using the wrong modifier at the outputFile.printf? Or wrong ".print()" line?
That's not how printf works; you give it a format then the things to print.
You're not passing anything to format with the %.2f, you're trying to add it. The docs provide info on how to use it (and there are many examples in the world).
Roughly:
outputFile.printf("Price = 4.56*" + qty + " = $" + "%.2f", price);
Although I'm not sure why you wouldn't do the same formatting for qty.

Print a multiline text document

I am having an issue with my code not printing out all of what is in a text document. My assignment is to take what is in a .txt file and put in a new .txt file I guess you could say "fancier."
This is the text file I am given.
Thomas Smith 3 2.25 44
Kim Johnson 2 55.60 35
John Doe 33 2.90 21
Karen Java 1 788.99 65
This is the "fancy" output I need(only It needs to output all of them).
The first name is: Thomas
The last name is: Smith
The total number of items bought is: 3
The customer's total is: 6.75
The customer's total rounded (cast) is: 6
The age of the customer is: 44
I think I have just been staring at it so long I'm just over looking it...
Scanner inFile = new Scanner(new FileReader("customer.txt"));
double options;
System.out.println("How would you like to input your data?\n1 Input information from customer.txt\n2 Input information from the keyboard.");
options = console.nextDouble();
if (options == 1){
//Variable to store first name
String firstName;
//Variable to store last name
String lastName;
//Variable to store how many items bought
int itemsBought;
//Variable to store the price per item
double itemPrice;
//Variable to store their age
int age;
while (inFile.hasNext()){
//Gets the first name
firstName = inFile.next();
//Gets the last name
lastName = inFile.next();
//Gets number of items bought
itemsBought = inFile.nextInt();
//Gets the price per item
itemPrice = inFile.nextDouble();
// Gets their age
age = inFile.nextInt();
PrintWriter outFile = new PrintWriter("programOutputFile.txt");
outFile.println("The customers first name is: " + firstName);
outFile.println("The customers last name is: " + lastName);
outFile.println("The customer bought " + (int)itemsBought + " items.");
outFile.println("The customers total is " + itemPrice);
outFile.println("The total cost rounded " + (int)itemPrice);
outFile.println("The customers age is: " + (int)age);
outFile.close();
}
}
else if (options == 2) {
String firstname;
String lastname;
int items = 0;
double price = 0;
int age1 = 0;
int counter; //loop control variable
counter = 0;
int limit; //store the number of items
System.out.print("Enter the number of entries you have "); //Line 1
limit = console.nextInt(); //Line 2
while (counter < limit) {
// It is asking for the user to input their first name
System.out.println("Please tell me what is your first name? ");
firstname = console.next();
// It is asking for the user to input their last name
System.out.println("What is your last name? ");
lastname = console.next();
// It is asking for the number of items they purchased
System.out.println("How many items did your purchase? ");
items = console.nextInt();
// Here it is asking for the total price they paid
System.out.println("What was the cost of each item? ");
price = console.nextDouble();
System.out.println("How old are you? ");
age1 = console.nextInt();
double total = items * price;
counter++;
if (counter != 0){
//Outputs the length of Firstname
System.out.println("The name is " + firstname.length() + " letters in your first name.");
//Outputs the first letter of LastName
System.out.println("The first letter of your last name is: " + lastname.charAt(0));
//Outputs the number of items bought
System.out.println("You bought " + items + " items.");
//Outputs Price
System.out.println("Your total price was " + total);
//Outputs the Price as a int number
System.out.println("Your total price rounded is " + (int)total);
//Outputs the age
System.out.println("They are " + age1 + " years old.");
PrintWriter outFile = new PrintWriter("programOutputFile.txt");
//Outputs the information given above into a .txt file
outFile.println("The customers first name is: " + firstname);
outFile.println("The customers last name is: " + lastname);
outFile.println("The customer bought " + (int)items + " items.");
outFile.println("The customers total is " + total);
outFile.println("The total cost rounded " + (int)total);
outFile.println("The customers age is: " + (int)age1);
outFile.close();
}
else
System.out.println("Invalid. Please try again.");
}
}
inFile.close();
}
As of right now it will print out Karen Java's line instead of Karen, John, Kim, and Thomas's. I have option 2 finished but again I am having the same problem of it only prints out the last input.
Any advise would be greatly appreciated!
You reopen the file in your loop each time you write. This has the effect of overwrite any previous contents of the file (the previous output you just wrote). declare outfile before the while loop and close it after.

Categories