System.out.printf("%-15s%03d%n", s1, x) How to interpret it - java

In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.
can someone explain the System.out.printf("%-15s%03d%n", s1, x);
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.next();
int x=sc.nextInt();
System.out.printf("%-15s%03d%n", s1, x);
}
System.out.println("================================");
}
}

Basically every %... is gonna be replaced by one of the arguments of printf. What is after the % sign is a format specifier.
In %-15s:
- means: left-justified
15 means: if the result is less than 15 characters long, add spaces until it is 15 characters long
s means: convert the parameter into a string with toString and use the result
In %03d:
0 means: pad with 0s instead of spaces
3 means: make it at least 3 characters long
d means: the argument will be an integer number, format it as a base-10 number.
%n is the same as \n on *NIX or \r\n on Windows.
You will get more info here: https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
EDIT based on remarks by AxelH and Andy Turner

Its Java formatter syntax
first half - %-15s
% - says that what follows is an argument that will be formatted.
s - says youre formatting a string
15 - number of characters you put into string
and finally - means string is gonna be justified to the left
second half - %03d
d means youll be adding integers
0 means youll be adding 0's where necessary
3 means you need to add 3 digits
%n is System.line_separator - basically outputs new line. It does the same as /n but %n is portable across platforms (credit #AxelH)

Related

Converting a hexadecimal string to integer value without pre-made syntax

I'm taking a computer organization class in college. I was tasked with writing a java program that takes a user-inputted string, calls a function that converts said string into a hexadecimal integer, and then outputs the results.
The kicker is that I can't use any existing syntax to do this. for example, Integer.parseInt(__,16) or printf. It all neds to be hardcoded.
Now I'm not asking you to do my homework for me, just wanting to be put in the right direction.
So far, I've made this but can't seem to get the method created right:
import java.util.*;
public class Demo_Class
{
public static void main(String[] args)
{
Scanner AI = new Scanner(System.in);
String str;
System.out.println("Please input a hexadecimal number: ");
str = AI.nextLine();
converter(str);
}
public static int converter(String in)
{
String New = new String();
for(int i = 0; i<= in.length(); i++)
{
New += in.charAt(i);
System.out.println(New + 316);
}
return 0;
}
}
Consider this, lets says you have the hex value 1EC which in hex digits would be 1, E, C. In decimal they would be 1, 14, 12.
so set sum = 0.
sum = sum*16 + 1. sum is now 1
sum = sum*16 + 14 sum is now 30
sum = sum*16 + 12 sum is now 492
So 492 is the answer.
If you have a string of 1EC you need to convert to characters and then convert those characters to the decimal equivalent of hex values.
Try this on paper until you get the feel and then code it. You can check your results using the Integer method you mentioned.
#WJS gave a good hint, I'd just like to add that the charAt() returns the char, which is encoded in ASCII.
As you can see in the ASCII table, the characters A-F have decimal values from 65 to 70, while 0-9 go from 48 to 57 so you'll need to use them to convert the ASCII characters to their intended value.
To do so, you can either get the decimal value of a character by casting to short like short dec = (short)in.charAt(i);, or directly use the characters like char current = in.charAt(i) - 'A'.
With this in mind, all that's left is some calculation, I'll leave that as the homework. :)
Also:
you are looping one character more than needed, change the i <= in.length() to i < in.length(), since it's going from 0
I don't know what that 316 "magic number" is, if it does mean something, declare a variable with a meaningful name, like:
final int MEANINGFUL_NAME = 316;

How to format 18 digit double to become 10 string character

double pdouble= 3.3603335204002837E12;
String pstart= Double.toString(pdouble).replace(".", "") .trim()
String.format("%10d", pstart);
System.out.println("pstart"+pstart);
Can I know why it not works...
It display this:
Exception in thread "main"
java.util.IllegalFormatConversionException: d != java.lang.String at
java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
.I
Hope anybody can help
%d is for int. As pstart is a String, Use b or s.
String.format("%10s", pstart);
Output
33603335204002837E12
Read Java String format()
However if you need only the first 10 digits from your number, try using DecimalFormat
DecimalFormat d = new DecimalFormat("0000000000");
String number = d.format(pdouble);
Output
3360333520400
This will also add leading 0s if the number is less than 10 digits.
For decimal numbers "f" flag needs to be used.
double pdouble= 3.3603335204002837E12;
System.out.println(String.format("%10f", pdouble));
This will print a string with minimum length of 10 chars.
In this pattern "%10f" the width flag (e.g. 10) is the minimum number of characters
The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.
from Formatter java doc

How to represent a 5 letter string as digit?

I want to create a numerical representation of 5 letter codes. The codes may have 1-5 letters or digits.
The number must of course be unique. It is not absolutely necessairy that those numbers can be converted back to the ascii.
Thus I need digits from 0 to ZZZZZ
The resulting number size should be as small as possible.
I started with the following, but it's not quite what I want:
String a="ZZZZZZ";
for (int i = 0; i < a.length(); ++i) {
System.out.print(a.charAt(i)-'A'+1);
}
ZZZZZZ=262626262626
000000=-16-16-16-16-16-16
Start by enumerating all possible "digits" of your number:
Ten decimal digits 0 through 9
Twenty six letters A through Z
You have 36 possible "digits" for five positions, so the max number is 365=60,466,176. This number fits in an int.
You can make this number by calling Integer.parseInt, and passing a radix of 36:
System.out.println(Integer.parseInt("ABZXY", 36)); // 17355958
Demo.
Keep in mind that A134Z is already a number; it is only printed in Base-36 representation!
Albeit being just one sentence, the above should give you all you need to know to translate any 5-character string with 0-9 and A-Z into a number (and back).
Simplest solution - if letters are case insensitive is to use radix of 36 - full alphabet plus 10 digits. That way you get both functions for free - converting from string to long and from long to string like this:
long numericCode = Long.parseLong("zzzzz", 36); // gives 60466175
String stringCode = Long.toString(numericCode, 36); // gives "zzzzz"
You can treat the string as a number in base36 (where A=10, B=11 ... Z=35). This way, you will use exactly the numbers from 0 to 36^5-1, and each will be used exactly once.

Changing Word to Numbers Java

For my current code, I'm creating a word calculator where words are inputted to represent numbers and the calculations are done within the code. The requirements is to input two numbers and an operator into the console. I was able to parse the input into three parts, the first number, the operator, and the second number.
My question is how should I approach when I convert the word into number form? For example, if a user inputted:
seven hundred eighty-eight plus ninety-five
How can I turn that into 788 and 95 so I can do the calculations within the code? My input needs to go up to 1000.
This is part of my code for dividing up the input.
import java.util.Scanner;
public class TextCalc2 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String in = input.nextLine();
in = in.toLowerCase();
while (!in.equals("quit")) {
if (in.contains("plus")){
String number1 = in.substring(0, in.indexOf("plus") - 1);
String number2 = in.substring(in.indexOf("plus") + 5, in.length());
String operator = in.substring(in.indexOf("plus"),in.indexOf("plus") + 5);
System.out.println(number1);
System.out.println(operator);
System.out.println(number2);
}
}
First of all there are problems in the way you are splitting the input (you have hard coded the operation). I would suggest splitting your input with " " (space) and then analyzing each part of the input separately.
You will have different types of words in your input, one is a single digit number, double digit number, operations and "hundred".
Then you should find which category first word of your input belongs to, if it has "-" it will be double digit, else look into other categories and search for it till you find it. Then based on category decide what you should do with it, if its a single digit, replace it with its equivalent. if its double digit, split and then replace each digit, if its operation store it and cut your input array from there so that you have separated the first value and second one, and if its hundred multiply previous single digit by 100.
After this parsing steps you will have something like this {"700","88"} , {"95"} and plus operation. now its easy to convert each string to its integer value using parse method and then apply the operation.
BTW, it would be easier to use Enum for your constants and just use their ordinal value. Also use the comment that Jared made for your double digit values.
Let me know if you still have question.

OutOfBounds Exception ; working with Fractions

I'm writing a program called FractionScaler that takes in a fraction from the user using Scanner, and then manipulates it. I've written a fraction class that handles all the calculations. The user is supposed to enter a fraction like this: "2/3" or "43/65" etc... This part works fine, the problem is when there is space between the integers: " 3 / 4 " or "2/ 5" etc... An "OutOfBoundsException: String index out of range: -1" occurs. Let me explain further.
//This is the user inputted fraction. i.e. "2/3" or " 3 / 4"
String frac = scan.next();
//This finds the slash separating the numerator from the denominator
int slashLocate = frac.indexOf("/");
//These are new strings that separate the user inputted string into two parts on
//either side of the "/" sign
String sNum = frac.substring(0,slashLocate); //This is from the beginning of string to the slash (exclusive)
String sDenom = frac.substring(slashLocate+1,frac.length()); //from 1 after slash to end of string
//This trims the white space off of either side of the integers
sNum = sNum.trim(); //Numerator
sDenom = sDenom.trim(); //Denominator
What I thought should be left is just two strings that look like integers, now I need to turn those strings into actual integers.
//converts string "integer" into real int
int num = Integer.parseInt(sNum);
int denom = Integer.parseInt(sDenom);
Now that I have two integers for the numerator and the denominator, I can plug them into a constructor for the fraction class I wrote.
Fraction fraction1 = new Fraction(num, denom);
I doubt this is the best way to go about this, but it is the only way I could think of. When the user inputted fraction has no spaces, EX. "2/3" or "5/6" , the program works fine.
When the user input has spaces of any kind, EX. "3 / 4" or " 3 /4" , the following error is shown:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1.
The terminal points to line 17 of my code which is this line above:
String sNum = frac.substring(0,slashLocate);
I don't know why I'm getting an out of bounds error. Can anyone else figure it out?
If something is unclear or I didn't give enough info, just say so.
Thanks very much.
Try String frac = scan.nextLine();
I think next() won't get anything after a space.
From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
That means this won't work, because when entering 2 / 3, frac will just contain the text "2":
String frac = scan.next();
//This finds the slash separating the numerator from the denominator
int slashLocate = frac.indexOf("/");

Categories