IllegalFormatPrecisionException while trying to format string - java

I'm trying to write a program which prompts the user to enter two 3×3 matrices and displays their product.
For example, a user can enter:
Matrix A: 2 4 6 8 10 12 14 16 18
Matrix B: 1 2 3 4 5.6 6.6 7.4 8.1 9
Below is what I have tried, but I keep getting this error. Any help to point me in the right direction would be appreciated. I'm trying to get it to one decimal place:
Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2892)
at java.util.Formatter$FormatSpecifier.(Formatter.java:2643)
at java.util.Formatter.parse(Formatter.java:2480)
at java.util.Formatter.format(Formatter.java:2414)
at java.io.PrintStream.format(PrintStream.java:920)
at java.io.PrintStream.printf(PrintStream.java:821)
at Exercise6_25.main(Exercise6_25.java:55)
import java.util.Scanner;
public class matrixCalc
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
int i,j,k;
int n=3;
double a[][]= new double[n][n];
double b[][]= new double[n][n];
double c[][]= new double[n][n];
System.out.println("enter the array elements of a:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=s.nextDouble();
}
System.out.print(" ");
}
System.out.println(" ");
System.out.println("enter the array elements of b:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=s.nextDouble();
}
System.out.print(" ");
}
System.out.println(" ");
System.out.println("the result matrix is:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf("%.2d", c[i][j]+" ");
}
System.out.println();
}
}
}

You are using the %d specifier, which requires an integer argument -- but you are giving it a String (because c[i][j]+" " converts c[i][j] to String when concatenating it).
Also, the %d specifier does not use a decimal point at all. Since integral types can be implicitly converted to floating-point types, the %f specifier is what you're looking for.
And finally, the number after the decimal point in the format specifier is what tells it how many decimal places to go to. You say you only want one decimal place, so let's make that a 1.
So what we end up with is this:
System.out.printf("%.1f ", c[i][j]);
See the Formatter Javadocs for a (somewhat mind-boggling) description of the all possible format specifiers. (Don't worry too much if you can't understand everything there; you'll never need most of it anyway.)

You can't format integers by using a decimal point in the conversion. Since c[i][j] is a double, you can use a floating point conversion:
System.out.printf("%.2f ", c[i][j]);
Instead of:
System.out.printf("%.2d", c[i][j]+" ");
See the help page for the formatter syntax for more information.

Are you sure you meant to say "%.2d" in your printf rather than "%.2f"?
You usually only use d for integer values, you have doubles in your matrix.

Your error is probably here:
System.out.printf("%.2d", c[i][j]+" ");
Check the documentation of how values are formatted when printed out.

Related

Reverse number using only loops;no Arrays,convert to String just beginner…Bug:Zero

I am trying to reverse random number from 1 to 9999, and got stuck with a bug zero:
Example: 23100 is the random number. my output is 132 but the solution is 00132
Since I still don't know Arrays, convert to String(manipulation), object solution etc…. I couldn't find a beginner-level solution for this problem.
Since this page helped me a lot, I decided to try to help someone. This is the beginners solution to problem:
123 reverse 321
12300 reverse to 00321 // bug problem with zero solved
I am still stuck with the problem: 00123 and output 32100 not 321
Here is my code:
import java.util.Scanner;
public class R_N{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("enter number:\n");
int x=input.nextInt();
int temp=x;
int z;
while(temp>0){
z=temp%10;
if(z==0){
System.out.printf("%d",0);
}else{
System.out.printf("%d",z);
}
temp=temp/10;
}
}
}
As I know, that kind of tasks not about using strings or something. It's all about properly use modulo and div.
00123 trailing zeroes have sence only if it's text value. 123 is a number. So your program works well for your task. But your if(z==0) have no sence :)
In order to reverse 00123 to 32100 you need to read the input as a String, then test if it contains only digits with a regular expression (such as \\d+), finally you could iterate it from the end printing each character. Something like,
Scanner input = new Scanner(System.in);
System.out.print("Please enter a number:\n");
System.out.flush();
while (input.hasNextLine()) {
String x = input.nextLine().trim();
if (x.matches("\\d+")) {
// Iterate the input String in reverse order,
for (int i = x.length() - 1; i >= 0; i--) {
// Print each character
System.out.print(x.charAt(i));
}
System.out.println();
} else {
// Give the user a message ...
System.out.printf("%s is not a number%n", x);
}
System.out.print("Please enter a number:\n");
System.out.flush();
}

Rounding Decimals in Java

So, I was making a program, where I have the user insert a numerator and denominator, the program converts the pseudo-fraction, to a decimal. It works fine, just one thing. One, if I enter a fraction that is a repeating decimal, (ex. 1/3, 0.3333333...), I want either it say 0.33 repeat, or for irrational numbers, It would round it after let's say 7 digits, and then stop and have "... Irrational" after. How could I do this? Code is below.
package Conversions;
import java.util.*;
public class FractionToDecimal {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
You could use this:
DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.CEILING);
Add as many # as you want decimals and then ou can simply use it like this:
Double d = 12345.789123456;
System.out.println(df.format(d));
Using three # would give you for the example above: 12345.789 for instance.
Please note that you can pick your rounding mode of course.
Small other note: Next time you ask a question on SO, please show some research, there are thousands of post about this and thousands of tutorials online. It would be nice to show what you have tried, what doesn't work ...

JAVA: use entered integer to define decimal places

this is my first entry to stackoverflow so please let me know if something is wrong.
I know how to show an imported float number with x decimal numbers. But how do you define the amount of decimal numbers via a new scanned int number?
This is my code: (of course "%.decimalf" doesn't work, I just wanted to test it)
anyone? thanks in advance!
import java.util.Scanner;
public class Fliesskommazahl{
public static void main (String[] args){
// ask for/import floating point number
System.out.println("Please enter a floating point number like 1,1234: ");
Scanner scanner = new Scanner(System.in);
float number = scanner.nextFloat();
// show floating point number
System.out.println("You've entered: " + number);
/* show number with exactly two decimal places
In short, the %.02f syntax tells Java to return your variable (number) with 2 decimal places (.2)
in decimal representation of a floating-point number (f) from the start of the format specifier (%).
*/
System.out.println("Your number with two decimal places: ");
System.out.printf("%.02f", number);
System.out.println();
// import second (positive) number.
System.out.println("Please enter a positive integer number to define amount of decimal places: ");
Scanner scanner2 = new Scanner(System.in);
int decimal = scanner.nextInt();
// show imported floating point number with imported number of decimal places.
System.out.printf("%.decimalf", number);
}
}
This could work
System.out.printf ("%." + decimal + "f", number);
You should use this class I think this could work out really good for you here it is:
double num = 123.123123123;
DecimalFormat df = new DecimalFormat("#.000");
System.out.println(df.format(num));
In this case the output would be 123,123, the amount of zeros after the #. is the amount of numbers you want after the dot.

Add two strings containing binary numbers

I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.
Anyway, I'm in a middle of an exercise that asks me to build a method that get two strings containing only the characters "0" and "1" from the user and returns one string of them both (binary)combined
example:
BinaryAdder("0","0") - > "0"
BinaryAdder("1","1") - > "10"
BinaryAdder("10100","111") - > "11011"
what I did is:
import java.util.Scanner;
public class assigment03
{
private static String whichIsBigger(String a, String b)
{
if(a.length()>b.length())
return a;
if(a.length()<b.length())
return b;
if(a.length()==b.length())
return a;
else return null;
}
private static String binaryAdder(String a,String b)
{
int[] binaryResult= new int[maxlength(a,b)+1];
String result="";
if(whichIsBigger(a,b)==a)
{
for(int i=0;i<b.length();i++)
{
binaryResult[i]=a.charAt(i)+b.charAt(i);
}
for(int i=b.length();i<a.length();i++)
{
binaryResult[i]+=a.charAt(i);
}
}
else
{
for(int i=0;i<a.length();i++)
{
binaryResult[i]=b.charAt(i)+a.charAt(i);
}
for(int i=a.length();i<b.length();i++)
{
binaryResult[i]+=b.charAt(i);
}
}
for(int i=0;i<binaryResult.length-1;i++)
{
if(binaryResult[i]>=2)
{
binaryResult[i]=binaryResult[i]%2;
binaryResult[i+1]++;
}
}
for(int i=binaryResult.length-1;i>=0;i--)
{
result+=Integer.toString(binaryResult[i]);
}
return result;
}
private static int maxlength(String a, String b)
{
if(a.length()>b.length())
return a.length();
else
return b.length();
}
public static void main(String[] args)
{
Scanner temp= new Scanner(System.in);
System.out.print(binaryAdder(temp.next(),temp.next()));
}
}
But it doesn't return the right result.
Do you mind help me out here?
thanks a lot!
Reading your question, I understood that you might be looking for some help implementing the methods to actually add two binary numbers, and then giving back the result in base two (which btw might be complicated in Java). However, I believe that this exercise lacks of a very important restriction like the what is max length allowed for the binary numbers to be read (overflows can arise while processing the values with primitive data types like int or String). Also this exercise needs some planning when dealing with none significant zeroes like in these cases because "00110b" = "0110b" = "0110b" and when dealing with rolling over the carry of any addition that yields 2 ("10b") or 3 ("11b"). More information on those topics can be found here, in chapter 2.
At least in Java, when tackling these type of exercises, an option is to avoid dealing with such restrictions and conditions. Java provides a class called BigInteger that takes care of huge values, none significant zeroes, and the carries taking away the burden of dealing with those things from the programmers. Java BigInteger also offers a constructor that can initialize their objects in any base. (Well not any, there are some restrictions to this too, please see this link for more information).
With that said, here is my solution to this exercise:
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
public class BinaryAdder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> numbers = new ArrayList<String>();
String number = "";
int count = 1;
System.out.print("Instructions:\nPlease enter a set of binary numbers. When you are ready to calculate their addition, enter \"done\",\n\n");
System.out.print("Number " + count + ": ");
while(!(number = scanner.next()).equals("done")){
numbers.add(number);
count++;
System.out.print("Number " + count + ": ");
}
System.out.print("Result = " + binaryAdder(numbers) + "b");
scanner.close();
}
public static String binaryAdder(ArrayList<String> numbers){
BigInteger accumulator = new BigInteger("0");
for(String number: numbers){
accumulator = accumulator.add(new BigInteger(number, 2));
}
return accumulator.toString(2);
}
}
Example:
Instructions: Please enter a set of binary numbers. When you are ready
to calculate their addition, enter "done",
Number 1: 00001
Number 2: 011
Number 3: done
Result = 100b
Between lines 8-11 some variables are declared: a scanner to read the binary numbers entered, an array list to store the binary numbers entered, a string to hold a number once is entered, and a int to keep track of how many numbers have been entered, since I extended this solution to add 0,1,2,3,...,n numbers).
Line 13 prints the instructions of this solution. Line 14 only prints "Number 1: ".
The while loop between lines 16-20 sets the value entered to the variable number and checks if it is equal to "done". Given the case it steps out of the loop, otherwise, it adds the number to the array list.
Line 22 prints the result of the addition of all the binary numbers entered.
But the "magic" really happens between lines 27-35 in the method "binaryAdder" (Note that "binaryAdder" receives that ArrayList holding all the numbers entered as a parameter). At line 28 an accumulator of type BigInteger is initialized to zero to hold the addition of all the numbers in the ArrayList. Then, a for loop travels through all the numbers in the array list to add them to the accumulator. Finally, the accumulated value is returned in base two.

incompatible types error

import javax.swing.JOptionPane;
public class Result
{
public static void main (String[] args)
{
int numa;
int numb;
int sum;
String num1 = JOptionPane.showInputDialog(null,"Enter 1st Number: ");
numa=Integer.parseInt(num1);
String num2 = JOptionPane.showInputDialog(null,"Enter 2nd Number: ");
numb=Integer.parseInt(num2);
{
sum=num1+num2;
}
if (sum>=10)
JOptionPane.showMessageDialog(null,"Congratulations"+sum);
else if(sum<10)
JOptionPane.showMessageDialog(null,"the sum of the number less than 10");
else if(sum>100)
System.exit(7);
}
}
This line:
sum=num1+num2;
is trying to add two strings together and make an int.
Instead, you want:
sum = numa + numb;
In other words, take the values you've just parsed from the strings, and add those together.
Additionally, I'd suggest:
Where possible, declare variables at the point where you first use them (typically assignment)
Don't add braces just for the sake of it (e.g. for this sum line) but...
... do add braces to all if blocks for clarity
Indent all code appropriately (there should never be two braces lining up as per the end of your method)
Unless you really need to use Swing, don't bother - this app would be simpler if it took input from the console and just wrote the answer to the console, instead of showing a message box.
sum = numa + numb
You were trying to add the two strings.
Edit: skeeted again!

Categories