The string is getting the wrong value - java

I am trying to build a string like 11 11 but I am facing problem I am getting for start the following string 98 11 and not 11 11.
How can I fix that?
I appreciate any help.
Character number = newName.charAt(2); //here number is 1
Character numberBefore = newName.charAt(1); //here numberBefore is 1
try (PrintWriter writer = new PrintWriter(path+File.separator+newName);
Scanner scanner = new Scanner(file)) {
boolean shouldPrint = false;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(numberBefore >0 ){
String start= number+number+" "+number+number; //here start is `98 11`
}

Yes, this is due to the associativity of +.
This:
String start= number+number+" "+number+number;
is effectively:
String start = (((number + number) + " ") + number) + number;
So you're getting number + number (which is performing numeric promotion to int) and then string concatenation.
It sounds like you want:
String numberString = String.valueOf(number);
String start = numberString + numberString + " " + numberString + numberString;
Or alternatively:
String start = String.format("%0c%0c %0c%0c", number);

yes this is because of associativity of +
you can try the below code also
String c1 =Character.toString(number);
String s =c1+c1+" "+c1+c1;

String newName = "111";
Character number = newName.charAt(2); // here number is 1
Character numberBefore = newName.charAt(1); // here numberBefore is 1
if (Character.getNumericValue(numberBefore) > 0) { // checking against numeric rather than ascii
System.out.println("ASCII value of char " + (int) number); // ASCII code for '1' = 49
String start = String.valueOf(number) + String.valueOf(number) + " " + number + number; // here start is `98 11`
System.out.println(start);
}
}

Related

Splitting a string that has numbers and characters into an int and String

I have a String that goes "Peyton Manning; 49". Is there a way to have the computer read the left side of the String and make it equal to a new String "Peyton Manning" and take the right side of the String and make it equal to an int with a value of 49?
A number of ways spring to mind: you can tokenize or you can use regexs. You didn't specify about white space padding. Also, you didn't specify if the string segments around the delimiter can be invalid integers, mixtures strings digits etc. If this helped you, please mark accordingly.
public class Test {
public static void main(String[] args) {
String s="Blah; 99";
StringTokenizer st = new StringTokenizer(s, ";");
String name = st.nextToken();
Integer number = Integer.parseInt(st.nextToken().trim());
System.out.println(name.trim() + "---" + number);
number = Integer.parseInt(s.replaceAll("[^0-9]", ""));
name = s.replaceAll("[^A-Za-z]", "");
System.out.println(name + "---" + number);
int split = s.indexOf(";");
name = s.substring(0, split);
number = Integer.parseInt(s.substring(split+2, s.length()));
System.out.println(name + "---" + number);
}
}
The simplest way is:
String text = input.replaceAll(" *\\d*", "");
int number = Integer.parseInt(input.replaceAll("\\D", ""));
See KISS principle.

How to generate employee Id?

So I'm creating an employee payroll system and the id requirements are:
must always be 10 characters long. The first seven are First 3 letters of first name, the middle initial(default is zero if no middlename), and the first 3 letters of last name
the last 3 chars are an incrementing value which represents the number of occurrences of the first 7 characters (eg. AAABCCC001, AAABCCC002, XXXYZZZ001,XXX0ZZZ001 etc).
I'm not sure how to approach this. Help Please!
This is the code I have so far:
count=1;
fnameSubstr= fname.substring(0,3).toUpperCase();
mInitial= mnames.substring(0,0).toUpperCase();
lnameSubstr= lname.substring(0,3).toUpperCase();
nameStr=fnameSubstr + mInitial + lnameSubstr + String.valueOf(count).format("%03d", count);
for (Employee e: emp_list){
if nameStr.equals(id){
intStr=nameStr.substring(7); //string representing the first 7 chars
strInt=Integer.parseInt(intStr);//string of the last 3 chars
if count==strInt{ //compares the count to the int value of the last 3 chars
count++;
nameStr=fnameSub + mInitial + lnameSub+String.valueOf(count).format("%03d",count);
}
}
else{
count=1;
nameStr=fnameSub + mInitial + lnameSub + String.valueOf(count).format("%03d", count);
}
}
I'm not sure if I'm on the right track.
Please use the below code
`
static Integer count = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(getEmployeeIdBy("DILIP","","DURAISWAMY"));
System.out.println(getEmployeeIdBy("KUTTY","","DILIP"));
System.out.println(getEmployeeIdBy("PANDA","R","SADASIBA"));
}
public static String getEmployeeIdBy(String firstName, String middleName, String lastName) {
String res1 = firstName.substring(0, 3);
String res2 = middleName.isEmpty() ? "0" : middleName.substring(0, 1);
String res3 = lastName.substring(0, 3);
String res4 = res1 + res2 + res3;
String res5 = count.toString().length() == 1 ? ("00" + count)
: count.toString().length() == 2 ? ("0" + count) : count.toString();
count = count + 1;
String finalResult = res4 + res5;
return finalResult;
}`
The final output would be
DIL0DUR000
KUT0DIL001
PANRSAD002
Get the letters of the from the name using substring method. set variables
String fName = //first three letters of the first name;
String mName = "0";
String lName = //first three letters of the last name;
if (/*mName is not null*/){
mName = //get the middle initial
}
create a counter = 1 to count how many ids you have made. Note that you can use String.format("%03d",counter) to format the counter in three digits; and lastly concatinate all your variables.

Why am I getting Runtime errors for substring - Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10

I want to be able to use the substring method or if you guys have a better suggestion, on how to take numbers from a text file containing some info and being able to divide num2 by 100 and multiply num1 by num2. I would like some insight on how to properly use the substring method.
This is what I have so far, although its not the full code(I got the other parts to work), I'd still appreciate if someone can help please.
also I am using one arraylist.
Text sample:
1 : 4.74 (93 % pa)
2 : 1.03 (92 % pa)
3 : 2.95 (99 % pa)
4 : 5.18 (61 % pa)
5 : 5.50 (81 % pa)
6 : 3.24 (55 % pa)
7 : 3.66 (64 % pa)
8 : 3.44 (98 % pa)
9 : 2.36 (76 % pa)
10 : 1.78 (94 % pa)
edit: Numbers are the decimal and percentage
edit2: Duh
edit3: Trying to solve this (Read this if you want to make it easier to understand what I am asking) http://csta.villanova.edu:8080/bitstream/2378/323/1/Forestry.html
case "Y": {
try {
FileReader text = new FileReader(mu + ".txt");
Scanner file = new Scanner(text);
//now read the file line by line...
int lineNum = 0;
while (file.hasNextLine()) {
String num1 = file.nextLine();
String num2 = file.nextLine();
String year1 = "";
num1 = year1.substring(4,9);
String year2 = "";
num2 = year2.substring(10,13);
try {
double nnum1 = Double.valueOf(num1.trim()).doubleValue();
double nnum2 = Double.valueOf(num2.trim()).doubleValue();
nnum2 /= 100;
nnum1 *= nnum2;
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
if(lineNum == projekt.size()) {
num1 = year1.substring(5,10);
num2 = year2.substring(11,14);
try {
double nnum3 = Double.valueOf(num1.trim()).doubleValue();
double nnum4 = Double.valueOf(num2.trim()).doubleValue();
nnum4 /= 100;
nnum3 *= nnum4;
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
lineNum++;
}
file.close();
} catch(FileNotFoundException e) {
System.out.println("Nope");
}
//ecree = new PrintWriter(mu + ".txt");
//height + height * percentage
// use substring to grab percentage from file
// remember to divide the percentage by 100 to show
}
break;
a) Not sure what the Scanner class does but it seems that you read 2 lines at once.
while (file.hasNextLine())
{
String num1 = file.nextLine();
String num2 = file.nextLine();
b) You should not overwrite your data: you read text into num1 but you assign a part of the empty string (year1) to it which for sure produces an index out of bounds exception:
String num1 = file.nextLine();
String year1 = "";
num1 = year1.substring(4,9);
you mean maybe
String num1 = file.nextLine();
String year1 = num1.substring(4,9);
c) you should be using java pattern matching in order to have a more generic approach (see https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
Pattern p = Pattern.compile("(\\d+)\\s*\\:\\s*(\\d+\\.\\d*)\\s*\\((d+).+");
String num1 = file.nextLine();
String year1 = o.match(num1.trim());
I have a feeling you are calling substring on the wrong variables.
String year1 = "";
num1 = year1.substring(4,9);
String year2 = "";
num2 = year2.substring(10,13);
You set year1 to "" then try to set num1 to a substring of "".
Looks like you want it the other way around.

For loop that prints from array

I am trying to print out two separate exam marks for students using a text file.
Below is a screenshot of the text file:
The first column is the student ID and the following two columns are both exam marks
Below is my code that does that calculations and prints:
//for loop that does calculations and prints
for(int i = 0; i < arraySize;i++){
String markOneFull = studentExamOneArray[i];
String markOneString = markOneFull.substring(5,7);
double markOne = Double.parseDouble(markOneString);
examOneNoID[i]= markOne;
String markTwoFull = studentExamTwoArray[i];
String markTwoString = markTwoFull.substring(8,10);
double markTwo = Double.parseDouble(markTwoString);
examTwoNoID[i] = markTwo;
/* String markThreeFull = studentExamThreeArray[i];
String markThreeString = markThreeFull.substring(5,10);
double markThree = Double.parseDouble(markThreeString);
examThreeNoID[i] = markThree;
String markFourFull = studentExamFourArray[i];
String markFourString = markFourFull.substring(5,10);
double markFour = Double.parseDouble(markFourString);
examFourNoID[i] = markFour;
*/
// Aggregate Mark
double aggregate = (examOneNoID[i] + examTwoNoID[i])/2;
DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
//time to write
write.println(studentArray[i] + "\nAB101: " + examOneNoID[i] + " " + " AB102: " + examTwoNoID[i] + " Overall Mark: " + oneDigit.format(aggregate));
write.println("----------------------------------------");
}
write.close();
}
When i run the program i get an error message saying:
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at MarksProcessing.main(MarksProcessing.java:42)
Try something like this:
Scanner sc = new Scanner(new File(fileName));
int i = 0;
while (sc.hasNext())
{
students[i] = sc.nextInt();
studentExamOneArray[i] = sc.nextDouble();
studentExamTwoArray[i] = sc.nextDouble();
double aggregate = (studentExamOneArray[i] + studentExamTwoArray[i])/2;
DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
System.out.println("Student: " + students[i] + " FirstGrade: " + studentExamOneArray[i] + " SecondGrade: " + studentExamTwoArray[i] + " Overal: " + oneDigit.format(aggregate));
i++;
}
Now, you don't need substring and so on. You know the structure of file with grades or whatever that file is. And you don't need extra arrays (you use one for strings and then one for doubles and so on). Just read the numbers into array, then do the math and print.
I think, the specified problem can be easily handled . As we can see that here we are parsing string type into different kind of datatypes , so we should try to catch a Number Format exception.

Return String formatted like a credit card number

I have a simple cardNumber String that I'm trying to Format for my System.out.ln
Here is the method that my System.out.ln calls
public String getCardNumber()
{
cardNumber = "0000 0000 0000 0000";
return cardNumber;
}
but the made up part of cardNumber = "0000 0000 0000 0000"; is what I'm trying to format it like, so 12345678912345752 becomes 1234 5678 9124 5752
I've had a look at substring() and stuff but I can't see a simple way to go through every 4 characters and insert a space automatically.
You just need to manually edit your string
String input = "1234567891245752";
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (i % 4 == 0 && i != 0) {
result.append(" ");
}
result.append(input.charAt(i));
}
System.out.println(result.toString());
See what we're doing here is iterating over your string, and adding a whitespace in between every 4 characters.
To add a space after every 4 characters in a 16 character string, do this.
String number = "1234123412341234";
number = number.substring(0,3) + " " + number.substring(4, 7) + " " + number.substring(8, 11) + " " + number.substring(12, number.length());
try out the following method:
public String getNumberString() {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat fmt = new DecimalFormat("0000,0000,0000,0000", symbols);
return fmt.format(this.number);
}

Categories