How to indent in Java using format - java

I am looking to indent a print line in Java using format but I'm a little confused by the process.
I searched around and found this which presents the following option:
String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
*/
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);
I implemented it in my own code in the following way:
public class Main {
public static void main(String[] args) {
// Take in user input for report title
System.out.println("Enter a title for this report");
String msg = "=> ";
String blank = "";
String format = "%-4s%s%n";
System.out.printf(format, blank, msg);
}
}
I tried removing the blank with the following:
public class Main {
public static void main(String[] args) {
// Take in user input for report title
System.out.println("Enter a title for this report");
String msg = "=> ";
String format = "%-4s%s%n";
System.out.printf(format, msg);
}
}
But I receive the following error in IntelliJ IDEA:
Exception in thread "main" java.util.MissingFormatArgumentException:
Format specifier '%s' at
java.base/java.util.Formatter.format(Formatter.java:2672) at
java.base/java.io.PrintStream.format(PrintStream.java:1053) at
java.base/java.io.PrintStream.printf(PrintStream.java:949) at
Main.main(Main.java:32)
My question is, why is that first string required? Is there a way to do it without declaring the "blank" variable I have? I apologize if this is answered somewhere, I searched but could not find it.
This is my desired output:
Enter a title for this report
=>

You just need to change your format string:
String format = "%8s%n";
Remove one %s as you are passing one less string compared to your example code and 8 is the indent for your second line.
Use the value 8 because 1 tab = 8 spaces.

This may work.
import java.util.Formatter;
public class Main {
public static void main(String[] args) {
System.out.println("Enter a title for this report");
String msg = "=>";
String output = String.format("%6s\n",msg); //7 th line
System.out.print(output);
}
}
In the 7th line I have specified (6s) means total string will be of length 6. msg is length of 2 then remaining 4 spaces will be assigned to left(if we mention "-6" 4spaces will be assigned to right) to the string msg

Related

Get String in a single or double line from ArrayList using string Buffer

I have an ArrayList that contains some elements and I am using String Buffer to get in a string. But When I am print the String I am getting in unorganized line. I want to get in single or double line.
ArrayList<String> mCombinedList; // it contains some value I have already instantiate it
StringBuilder builder = new StringBuilder();
for (String singleLine : mCombinedList) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(singleLine);
}
String string = builder.toString();
Log.e(TAG, "string builder " +string );
After Implementing this code I am getting this result in Log.
abdul jani
456
Friend User 3
721015***
Friend
**ArrayList value of mCombinedList; **
[ abdul jani
456
Friend, User 3
721015***
Friend]
During the final phase of your String build using StringBuilder, when you have collected all the strings, just call this regex to remove all the white spaces that are more than 2 which will clean up all the additional white spaces that got introduced due to empty strings in your source arraylist
String string = builder.toString().replaceAll("\\s{2,}", " ").trim();
You are adding lot of spaces by builder.append(" ");. Use of ArrayList.toString() will solve your problem.
package com.test;
import java.util.ArrayList;
public class ListToString {
public static void main(String[] args) {
ArrayList<String> mCombinedList = new ArrayList<>();
mCombinedList.add("abdul jani");
mCombinedList.add("456");
mCombinedList.add("Friend");
mCombinedList.add("User");
mCombinedList.add("3");
mCombinedList.add("721015****");
mCombinedList.add("Friend");
String string = mCombinedList.toString();
//System.out.println(string);
Log.e(TAG, "string builder " +string );
}
}
Output:
[abdul jani, 456, Friend, User, 3, 721015****, Friend]

What is the simplest way to write the output of a Java document to a .rtf file?

I am wondering what the easiest way to write the output (last line of non-commented code below) to a .rtf file so that I can format some aspects with italics as well as keep a continuous, copy and paste-able, list of all my citations. Is there a way to do what I want that is simple? I am a beginner at Java and don't want anything too complicated to deal with.
/* (c) Tyler Holley January, 2018
* CitationGenerator Version 0.2
*
* User inputs academic source information and gets a proper citation back ready for copy and pasting into a Works Cited page.
*/
import java.util.Scanner;
class CitationGenerator {
public static String bookFormat(String author, String title, String publisher, int pubDate) {
//
String bFormat = author + ". " + title + ", " + publisher + ", " + pubDate + ".";
return bFormat;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String error1 = "ERROR: INVALID INPUT."; // Catchall error
String errorN = "ERROR: No other formats are currently supported in this version."; // Filler error while WIP
System.out.println("Welcome to CitationGenerator v0.1!");
System.out.print("What format is your citation in? MLA/APA/Chicago: "); // Add APA/Chicago support
String format = in.next();
if (format.equalsIgnoreCase("MLA")) { // equalsIgnoreCase ignores case inputted so MLA, mLa, mla, etc. are all valid
System.out.print("\nIs your source a book, website, or other? ");
String sourceType = in.next();
// Try and figure out how to clear the console after the user inputs sourceType
if (sourceType.equalsIgnoreCase("book")) {
System.out.print("\nAuthor's First Name: ");
String fName = in.next();
System.out.print("Author's Last Name: ");
String lName = in.next();
in.nextLine();
System.out.print("\nBook Title: ");
String title = in.nextLine();
System.out.print("\nPublisher Name: ");
String publisher = in.nextLine();
System.out.print("\nPublication Date: ");
int pubDate = in.nextInt();
String author = lName + ", " + fName; // Converts fName and lName to one concatonated String
System.out.println("\n\nHere is your citation! Don't forget to italicize the title!\n");
// Try to automatically italicize text when converting program to a .rtf
System.out.println(bookFormat(author, title, publisher, pubDate));
// GOAL: Alternate to the println below :
//System.out.println("\n\nYour citation is ready, would you like to save it to a/the .rtf document? y/n");
// This would branch into an if/else statement to print either to a document or continue to terminal output.
}
}
}
Pretty similar to writing to any file:
DataOutputStream dos;
File file = new File("\\your\\file\\path\\file.rtf");
try {
dos = new DataOutputStream(new FileOutputStream(file));
dos.writeBytes(bookFormat(author, title, publisher, pubDate));
dos.close();
catch( //IOexception or similar etc
Output:
surname, firstname. booktitle, bookpublisher, 1234.

separating lines of printed text when using printf

Working on a project that requires something to be printed as "printf" but the next line then ends up on the same line as the previous one, how would I go about seperating these?
System.out.print("Cost per course: ");
double costPerCourse1;
costPerCourse1 = keyboard.nextDouble();
System.out.printf("%.2f", costPerCourse1 + /n);
double tuition;
tuition = numberOfClasses1 * costPerCourse1;
System.out.println("Tuition: " + tuition);
You're trying to pass a new line character into the argument String, something that I don't think work. Better is to include "%n" within the format String passed into printf and that will give you an OS independent new line. For example:
System.out.printf("%.2f%n", costPerCourse1);
Or you could simply follow your printf with an empty SOP call.
Edit
I'm wrong. An argument String can have a valid newline char and it works:
public class TestPrintf {
public static void main(String[] args) {
String format1 = "Format String 1: %s";
String arg1 = "\nArgument String 1 that has new line\n";
System.out.printf(format1, arg1);
String format2 = "Format String 2 has new line: %n%s%n";
String arg2 = "Argument String2 without new line";
System.out.printf(format2, arg2);
}
}
returns:
Format String 1:
Argument String 1 that has new line
Format String 2 has new line:
Argument String21 without new line
Or:
System.out.printf("%s: %.4f%s%s", "Value:", Math.PI, "\n", "next String");
returns:
Value:: 3.1416
next String

Having an issue with formatting a String input

I'm trying to get the input that the user enters to go to lower-case and then put the first character in the input to upper-case. For example, If I enter aRseNAL for my first input, I want to format the input so that it will put "Arsenal" into the data.txt file, I'm also wondering if there's a way to put each first character to upper-case if there's more than one word for a team ie. mAN uNiTeD formatted to Man United to be written to the file.
The code I have below is what i tried and I cannot get it to work. Any advice or help would be appreciated.
import java.io.*;
import javax.swing.*;
public class write
{
public static void main(String[] args) throws IOException
{
FileWriter aFileWriter = new FileWriter("data.txt");
PrintWriter out = new PrintWriter(aFileWriter);
String team = "";
for(int i = 1; i <= 5; i++)
{
boolean isTeam = true;
while(isTeam)
{
team = JOptionPane.showInputDialog(null, "Enter a team: ");
if(team == null || team.equals(""))
JOptionPane.showMessageDialog(null, "Please enter a team.");
else
isTeam = false;
}
team.toLowerCase(); //Put everything to lower-case.
team.substring(0,1).toUpperCase(); //Put the first character to upper-case.
out.println(i + "," + team);
}
out.close();
aFileWriter.close();
}
}
In Java, strings are immutable (cannot be changed) so methods like substring and toLowerCase generate new strings - they don't modify your existing string.
So rather than:
team.toLowerCase();
team.substring(0,1).toUpperCase();
out.println(team);
You'd need something like:
String first = team.substring(0,1).toUpperCase();
String rest = team.substring(1,team.length()).toLowerCase();
out.println(first + rest);
Similar as #DNA suggested but that will throw Exception if String length is 1. So added a check for same.
String output = team.substring(0,1).toUpperCase();
// if team length is >1 then only put 2nd part
if (team.length()>1) {
output = output+ team.substring(1,team.length()).toLowerCase();
}
out.println(i + "," + output);

Using a pipe character as a delimiter, but getting an invalid escape sequence error on it?

I'm not certain why I'm getting an "invalid escape sequence" error for using "\|", since it's supposed to make it just a | character? I'm attempting to read in a file, where values are separated by a | character, and for some reason it's giving me a very odd output. I have a text file:
Star Trek|Sci-fi|Sy-fy|48|is
Word Girl|Children's|PBS Kids|21|is
Firefly|Sci-fi|FOX|50|is
America's Next Top Model|Drama|CNN|51|is not
Being Human|Sci-fi|Sy-fy|48|is not
Black Mirror|Anthology|Channel 4|55|is
Grandma's House|Comedy|BBC Two|26|is
Sherlock|Crime drama|BBC One|55|is
Psych|Comedy-Drama|ION|51|is not
The Big Bang Theory|Sitcom|CBS|23|is not
I would like to go through this text file line by line, and then pass it through a TV shows class, which is as follows:
public class TVShows {
private String showName;
private String genre;
private String network;
private String favourite;
private String runningTime;
public TVShows(String showName, String genre, String network, String favourite, String runningTime){
this.genre = genre;
this.showName = showName;
this.network = network;
this.runningTime = runningTime;
this.favourite = favourite;
}
public String toString(){
return showName + ", on " + network + ", a " + genre + " show with a running time of " + runningTime + " minutes. This "
+ favourite + " a favourite.";
}
}
It's all very simple, but for some reason, when I implement it in the driver, which is here:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
File myFile = new File("./src/TVShows.txt");
Scanner fileScanner = new Scanner(myFile);
while(fileScanner.hasNextLine())
{
TVShows myShows = new TVShows("test","test","test","test","test");
String line = fileScanner.nextLine();
System.out.println(fileScanner.nextLine());
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter("\|");
while(lineScanner.hasNext())
{
System.out.println(lineScanner.next());
String showName = lineScanner.next();
String genre = lineScanner.next();
String network = lineScanner.next();
String runningTime = lineScanner.next();
String favourite = lineScanner.next();
TVShows myShows1 = new TVShows(showName, genre, network, favourite, runningTime);
System.out.println(myShows1);
}
}
}
}
I get an invalid escape sequence error on "\|". Why is this? Do I just need to put another backslash in? Like "\|"? When I do this, and run the program, I get the output:
ÿþS t a r T r e k
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Program3.Driver.main(Driver.java:30)
This is line 30:
String favourite = lineScanner.next();
Thanks for any help.
you should use two backslash in java
lineScanner.useDelimiter("\\|");
You need two backslashes:
lineScanner.useDelimiter("\\|");
First one is to escape the second one from parsing in the compiler. They together make a single backslash in the string constant that is used to escape the pipe symbol in the regex engine.
This section of code
while(lineScanner.hasNext())
{
System.out.println(lineScanner.next());
String showName = lineScanner.next();
String genre = lineScanner.next();
String network = lineScanner.next();
String runningTime = lineScanner.next();
String favourite = lineScanner.next();
}
involves checking hasNext() once, then running next() six times. Therefore, if you have a number of elements not divisible by six, you will inevitably have some n<6 number of elements left, get n elements, then get an error on trying to get the n+1th element.
From your data, I assume you are supposed to have 5 elements, not 6. I'm guessing that your println is disrupting the flow by requesting an extra element. Delete it and add System.out.println(showName); somewhere after you define showName; this should fix your problem.

Categories

Resources