How to print this output in Java Top students: 33.33%? - java

My output is different ,I got
Top students: 30.00%nBetween 4.00 and 4.99: 30.00%nBetween 3.00 and 3.99: 20.00%nFail: 20.00%n Average: 4.06
I tried:
System.out.printf("Top students: %.2f%%n",p5);
System.out.printf("Between 4.00 and 4.99: %.2f%%n",p4);
System.out.printf("Between 3.00 and 3.99: %.2f%%n",p3);
System.out.printf("Fail: %.2f%%n ",p2);
System.out.printf("Average: %.2f",avg);
It should be -every student and given data in every new interval on new line:
Top students: 30.00%
Between 4.00 and 4.99: 30.00%
Between 3.00 and 3.99: 20.00%
Fail: 20.00%
Average: 4.06
How to fix it?

The problem is that the percent characters have special meaning in a String passed to printf. Printing a literal percent character requires doubling it: ”%%”. Because these strings contain %%n, the first % escapes the second one, resulting in a literal %, then the n is treated as a literal n and included in the output.
To print a literal percent character followed by a newline, you should use %%%n.
For example:
System.out.printf("Top students: %.2f%%%n",p5);

Related

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

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)

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.

Java reading .txt file to array

I've been trying to workout this excersise all day, but not having any luck. Thanks in advance for any help.
Here's the problem
The approach you are to implement is to store each integer in an array
of digits, with one digit per array element. We will be using arrays
of length 50, so we will be able to store integers up to 50 digits
long. We have to be careful in how we store these digits. Consider,
for example, storing the numbers 38423 and 27. If we store these at
the “front” of the array with the leading digit of each number in
index 0 of the array, then when we go to add these numbers together,
we’re likely to add them like this:
38423
27
To simulate this right-shifting of values, we will store each value as
a sequence of exactly 50 digits, but we’ll allow the number to have
leading 0’s. For example, the problem above is converted into:
0000000000000000000038423
0000000000000000000000027
Now the columns line up properly and we have plenty of space at the
front in case we have even longer numbers to add to these.
The data for your program will be stored in a file called sum.txt.
Each line of the input file will have a different addition problem for
you to solve. Each line will have one or more integers to be added
together. Take a look at the input file at the end of this write-up
and the output you are supposed to produce. Notice that you produce a
line of output for each input line showing the addition problem you
are solving and its answer. Your output should also indicate at the
end how many lines of input were processed. You must exactly reproduce
this output.
You should use the techniques described in chapter 6 to open a file,
to read it line by line, and to process the contents of each line. In
reading these numbers, you won’t be able to read them as ints or longs
because many of them are too large to be stored in an int or long. So
you’ll have to read them as String values using calls on the method
next(). Your first task, then, will be to convert a String of digits
into an array of 50 digits. As described above, you’ll want to shift
the number to the right and include leading 0’s in front. The String
method charAt and the method Character.getNumericValue will be helpful
for solving this part of the problem.
You are to add up each line of numbers, which means that you’ll have
to write some code that allows you to add together two of these
numbers or to add one of them to another. This is something you
learned in Elementary School to add starting from the right, keeping
track of whether there is a digit to carry from one column to the
next. Your challenge here is to take a process that you are familiar
with and to write code that performs the corresponding task.
Your program also must write out these numbers. In doing so, it should
not print any leading 0’s. Even though it is convenient to store the
number internally with leading 0’s, a person reading your output would
rather see these numbers without any leading 0’s.
You can assume that the input file has numbers that have 50 or fewer
digits and that the answer is always 50 digits or fewer. Notice,
however, that you have to deal with the possibility that an individual
number might be 0 or the answer might be 0. There will be no negative
integers in the input file.
You should solve this problem using arrays that are exactly 50 digits
long. Certain bugs can be solved by stretching the array to something
like 51 digits, but it shouldn’t be necessary to do that and you would
lose style points if your arrays require more than 50 digits.
The choice of 50 for the number of digits is arbitrary (a magic
number), so you should introduce a class constant that you use
throughout that would make it easy to modify your code to operate with
a different number of digits.
Consider the input file as an example of the kind of problems your
program must solve. We might use a more complex input file for actual
grading.
The Java class libraries include classes called BigInteger and
BigDecimal that use a strategy similar to what we are asking you to
implement in this program. You are not allowed to solve this problem
using BigInteger or BigDecimal. You must solve it using arrays of
digits.
Your program should be stored in a file called Sum.java.
Input file sum.txt
82384
204 435
22 31 12
999 483
28350 28345 39823 95689 234856 3482 55328 934803
7849323789 22398496 8940 32489 859320
729348690234239 542890432323 534322343298
3948692348692348693486235 5834938349234856234863423
999999999999999999999999 432432 58903 34
82934 49802390432 8554389 4789432789 0 48372934287
0
0 0 0
7482343 0 4879023 0 8943242
3333333333 4723 3333333333 6642 3333333333
Output that should be produced
82384 = 82384
204 + 435 = 639
22 + 31 + 12 = 65
999 + 483 = 1482
28350 + 28345 + 39823 + 95689 + 234856 + 3482 + 55328 + 934803 = 1420676
7849323789 + 22398496 + 8940 + 32489 + 859320 = 7872623034
729348690234239 + 542890432323 + 534322343298 = 730425903009860
3948692348692348693486235 + 5834938349234856234863423 = 9783630697927204928349658
999999999999999999999999 + 432432 + 58903 + 34 = 1000000000000000000491368
82934 + 49802390432 + 8554389 + 4789432789 + 0 + 48372934287 = 102973394831
0 = 0
0 + 0 + 0 = 0
7482343 + 0 + 4879023 + 0 + 8943242 = 21304608
3333333333 + 4723 + 3333333333 + 6642 + 3333333333 = 10000011364
Total lines = 14
My code thus far
public class Sum {
public static void main(String args[]) throws FileNotFoundException{
File file = new File("sum.txt");
Scanner scanner = new Scanner(file);
String[] myInts = new String[50];
int mySpot = 0;
while(scanner.hasNext()){
myInts[mySpot] = scanner.next();
mySpot++;
}
for(int i = 0; i < myInts.length; i++){
}
System.out.println(Character.getNumericValue(myInts[0]));
System.out.println(Arrays.toString(myInts));
}
}
When all else fails read the instructions:
"The approach you are to implement is to store each integer in an array of digits, with one digit per array element. We will be using arrays of length 50, so we will be able to store integers up to 50 digits long."
Tells me that this line:
String[] myInts = new String[50];
Has some significant problems.
Tip 1: Don't call it myInts when it's an array of String objects. Things are hard enough already.
Tip 2: Understand that new String[50] is not going to give you a string sized to 50 characters. It's going to give you space to store references to 50 string objects.
Tip 3: Understand that each line of your input can be solved separately so there is no need to remember anything from the lines you've solved before.
Tip 4: Read one line at a time into String line;
Tip 5: After reading a line solve the display problem in two parts: left side and right side of ='s.
Tip 6: Left side: display the line with spaces replaced with space + space. line.replace(" "," + ");
Tip 7: Right side: use line.split(" ") to split line on space, loop the split array of strings, each of these strings is what you'll be converting to int arrays.
Tip 8: "convert a String of digits into an array of 50 digits" <- Life will be easier if you write a method that does this. Take a String. Return an int[]. private int[] makeIntArray(String num) Take care of the "right shifting/leading zero" problem here.
Tip 9: int and long aren't big enough to hold the bigger numbers so break the number String down to Strings of digits before converting to int[].
Tip 10: Read Splitting words into letters in Java
Tip 11: Read Split string into array of character strings
Tip 12: Once you have single characters you can use Integer.parseInt(singleCharString[index--]) if you broke it down to an array of strings or Character.digit( chr[index--], 10); if you broke it down to an array of characters.
Tip 13: "write some code that allows you to add together two of these numbers or to add one of them to another." Read that carefully and it tells you that you really need to declare two vars. int[] sum = new sum[SIZE]; and int[] next = new next[SIZE]; where size is private final static int SIZE = 50;
Tip 14: adding two of these int[] numbers to produce a new int[] would be another good time to make a method. int[] sum(int[] op1, int[] op2)
Tip 15: Since all our int[]'s are right shifted already and always 50 long start a loop with i at 49 and count down. result[i-1] = (op1[i] + op2[i] + carry) % 10; and carry = (op1[i] + op2[i] + carry) / 10 will come in handy. Make sure to stop the loop at 1 or [i-1] will go index out of bounds on you.
Tip 16: Test, Test, and Test again. Make small changes then test. Small change, test. Don't just type and pray. Use the debugger if you like but personally I prefer to check values like this System.out.println("line: " + line);//TODO remove debugging code
Tip #1: Initialize the array with 0. That way, when you process the file, all you have to worry about is to replace the index locations with the digits obtained from your file.
Tip #2: You have to do some repeated division by 10 and modulus operation to extract the digits from the number (or binary shift if you prefer). For example, to split the the digits from '27', you can do 27 % 10 (7) and 27 / 10 (2). The key here is to store the result as int. After all, each digit is a whole number (not a floating point number). For number of greater magnitude, you will need to discard the process digit position so that the number gets smaller. You will now when you are done when the quotient of the division is equal to zero. Therefore, you can say in pseudo-code: DIVIDE number by 10 WHILE number > 0 (something like that)
Tip #3, you will have to iterate in reverse to store the digits in the array. If the array has a length of 50, you will start with LENGTH-1 and count down to ZER0.
Tip #4: Use an array of ints not an array of Strings if the problem allows you to. Use Integer.parseInt(String s) to convert the numeric String to a primitive int.
I think the question says to read each digit into a different array of standard size while you are reading all the words into a same a same array. and it will also be good to process this line by line
something like this
Scanner scanner = new Scanner(file);
int[][] myInts = new int[wordSize][];
int mySpot = 0;
while (scanner.hasNextLine()) {
Scanner scanner1 = new Scanner(scanner.nextLine());
while (scanner1.hasNext()) {
String s = scanner1.next();
int i;
for ( i= 0; i < wordSize - s.length(); i++) {
myInts[i][mySpot] = 0;
}
i--;
for (int j=0;j < s.length(); i++,j++) {
myInts[i][mySpot] = Character.digit(s.charAt(i), 10);
}
mySpot++;
}
// do the additions here and add this line to output file
}

Java: set precision of numbers in applet

I have a problem in setting the precision of a non-output line.
This line of code writes the string on an applet.
g.drawString( "The numbers entered are: " + number1 +", "+number2 +", "+ number3, 25, 25 );
number1,number2 and number3 are three numbers of input. Now I want to see the output of the three numbers in 3 decimals. How can I write this line without changing the actual value of the numbers?
String.format gives you control over the format of interpolated values, like sprintf in C. It uses these format specifiers.
g.drawString(String.format("The numbers entered are: %.3f, %.3f, %.3f", number1, number2, number3), 25, 25)

Categories