I have an abstract class that contains a variable of type String declared moneyString
String moneyString;
It contains data something like $123,456,789
So inside the abstract class I have function
void convertToInt(){
remove(',');
remove('$');
empMoney = Integer.parseInt(moneyString.substring(0, moneyString.length()) );
}
And my remove function
void remove(char character){
boolean moreFound = true;
String tempString;
int index;
do{
index = moneyString.indexOf(character);
tempString = moneyString;
if(index!=-1){
//From beggining to the character
moneyString = moneyString.substring(0,index);
//After the character to the end
tempString = tempString.substring(index,tempString.length());
moneyString += tempString;
}
else{
moreFound = false;
}
} while(moreFound);
} //END remove()
Isn't it supposed to get out of the loop when when moreFound = false?
The issue with your code is here,
tempString = tempString.substring(index,tempString.length());
Should be index + 1 because you don't want to include that character.
tempString = tempString.substring(index + 1,tempString.length());
But, I suggest you use a DecimalFormat and parse(String) the value. Like,
public static int convertToInt(String money) throws ParseException {
NumberFormat df = new DecimalFormat("$#,###");
return df.parse(money).intValue();
}
Then you can call it like
public static void main(String[] args) {
try {
System.out.println(convertToInt("$123,456,789"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is
123456789
Indeed you have to change the line:
tempString = tempString.substring(index,tempString.length());
to:
tempString = tempString.substring(index+1,tempString.length());
The assignment could be done to a variable of type Long:
moneyString="$123,456,789,101";
long empMoney;
remove('$');
remove(',');
empMoney = Long.parseLong(moneyString.substring(0, moneyString.length()) );
Related
I have this assignment below:
I have two methods that modify strings simultaneously.
I have searched on many posts but couldn't find the answer.
I want the second method to modify (call) the result of the first one.
I am a neophyte to Java so thanks for your patience and understanding.
Assignment:
Part 1 - Normalize Text
Write a method called normalizeText which does the following:
Removes all the spaces from your text
Remove any punctuation (. , : ; ’ ” ! ? ( ) )
Turn all lower-case letters into upper-case letters
Return the result.
The call normalizeText(“This is some \“really\” great. (Text)!?”)
should return
“THISISSOMEREALLYGREATTEXT”
Part 2 - Obfuscation
Write a method called obify that takes a String parameter (the message to be obfuscated) and returns a string in which every vowel (A, E, I, O, U, Y) is preceded by the letters “OB” (be sure to use capital letters).
If we call obify on “THISISSOMEREALLYGREATTEXT”, it should return
“THOBISOBISSOBOMOBEROBEOBALLOBYGROBEOBATTOBEXT”
My code:
public class CryptoAssessment {
public static void main(String[] args) {
normalizeText("This is some \“really\” great. (Text)!?");
}
public static void normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print(Result_after_Normalization);
}
public static void Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print(Result_after_Obfuscation);
}
}
To pass the result of a call to method1() to a call to method2():
method2(method1("foo"))
To complete your assignment:
public static void normalize(String str) {
return str.replaceAll("\\W", "").toUpperCase();
}
public static void obfuscate(String str) {
return str.replaceAll("[AEIOU]", "OB$0");
}
Ah, I get your problem. You don't want to simply pring on the Console System.out - you need to return those strings back to the caller.
public static String normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print("After normalization: "+Result_after_Normalization);
return Result_after_Normalization;
}
And lets make the other one return a String as well
public static String Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print("After obfuscation: "+Result_after_Obfuscation);
return Result_after_Obfuscation;
}
And now the main() becomes this:
public static void main(String[] args) {
String result = obfuscate(normalizeText("This is some \“really\” great. (Text)!?"));
System.out.println("Result after doing both: "+result);
}
Was typing this out last night when i ran out of battery, so ergo the delay in answering.
You can use a method's return as another method's argument, as long as the type match.
First change your methods' signature like this(make them to return a value):
public static String normalizeText(String string_to_encrypt){...}
public static String Obfuscation(String string_to_Obfuscate){...}
Then you can use the return value:
String temp = normalizeText("This is some \“really\” great. (Text)!?");
String result = Obfuscation(temp);
Or:
String result = Obfuscation(normalizeText("This is some \“really\” great. (Text)!?"));
import java.util.Scanner;
public class SolverTester
{
public static void main(String[] args)
{
String symbolSubtract;
String symbolMultiply;
String symbolAddition;
String symbolDivide;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your equation: ");
int numberFirst = sc.nextInt();
if(sc.findInLine("-").equals("-"))
{
symbolSubtract = sc.findInLine("-");
} else if(sc.findInLine("*").equals("*"))
{
symbolMultiply = sc.findInLine("*");
} else if(sc.findInLine("+").equals("+"))
{
symbolAddition = sc.findInLine("+");
} else if(sc.findInLine("/").equals("/"))
{
symbolDivide = sc.findInLine("/");
}
int numberSecond = sc.nextInt();
Solver s = new Solver(numberFirst, numberSecond);
if(symbolSubtract.equals("-"))
{
s.subtraction();
System.out.println(s.getAnswer());
} else if(symbolMultiply.equals("*"))
{
s.multiplication();
System.out.println(s.getAnswer());
} else if(symbolDivide.equals("/"))
{
s.division();
System.out.println(s.getAnswer());
} else if(symbolAddition.equals("+"))
{
s.addition();
System.out.println(s.getAnswer());
}
}
}
My error is "variable "symbolSubtract" has not been initialized". The main class is not relevant because the error is involving local variables.
NOTE: This is not a homework assignment... I am just doing it for fun.
if(sc.findInLine("-").equals("-"))
{
symbolSubtract = sc.findInLine("-");
^^^^^^^^^^^^^^---conditional initialization
Only if that if() succeeds will the variable get a value.
But on this line
if(symbolSubtract.equals("-"))
you ALWAYS access the variable, meaning that only SOME of the time will it have a value.
If sc.findInLine("-") does not equal "-", symbolSubtract never gets initialized, so you can't use it. The easiest way around this, IMHO, is just to initialize it with a default value:
String symbolSubtract = "";
IF you change this:
String symbolSubtract;
String symbolMultiply;
String symbolAddition;
String symbolDivide;
to this
String symbolSubtract = "";
String symbolMultiply = "";
String symbolAddition = "";
String symbolDivide = "";
It should work.
You need to initialized your variables like this
String symbolSubtract="-";
String symbolMultiply="*";
String symbolAddition="+";
String symbolDivide="/";
or
String symbolSubtract=null;
String symbolMultiply=null;
String symbolAddition=null;
String symbolDivide=null;
The second way often result in NPE if you do any operation on it.
Other problem is findInLine(String) read the javadoc
I have 3 vectors with similar format like the following..
Vector1:
start:231 stop:234 name:xyz
start:331 stop:334 name:abc
start:431 stop:434 name:fds
Vector2 and vector3 also have same format.
I have to iterate the 3 vectors and split the contents and assign to strings or integers.
I have done like the following:
public static Tokens getTokens( Vector<NameBuffer> vc1 ) {
Tokens tokens=new Tokens();
Iterator it1=vc1.iterator();
while(it1.hasNext())
{
String onerecord= it1.next().toString();
StringTokenizer stringTokenizer = new StringTokenizer(onerecord);
while (stringTokenizer.hasMoreElements()) {
String tmp = stringTokenizer.nextToken();
if ( tmp.startsWith("start=")) {
tmp = tmp.substring("start=".length());
try {
int begin = Integer.parseInt(tmp);
tokens.setbegin(begin);
}
catch ( NumberFormatException nfe ) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format");
}
String tmp1 = stringTokenizer.nextToken();
if ( tmp1.startsWith("stop=")) {
tmp1 = tmp1.substring("stop=".length());
try {
int end = Integer.parseInt(tmp1);
tokens.setend(end);
//System.out.println(end);
}
catch ( NumberFormatException nfe ) {
nfe.printStackTrace();
}
}
else {
System.err.println("Wrong format");
}
String tmp2 = stringTokenizer.nextToken();
if ( tmp2.startsWith("name=")) {
tmp2 = tmp2.substring("name=".length());
String name = tmp2;
tokens.setname(name);
}
}
else {
System.err.println("Wrong format");
}
}//while(stringtokenizer.hasmoreElements
System.out.println(tokens);// At this point i was able to print all records
}//while(it1.hasNext()
return tokens; //Is the problem with this return?
}//getTokens
Note:Tokens is a simple Java class with setters and getters like setstart() and gerstart()
In the main method
public static void main(String[] args) {
Tokens fnTokens=getTokens(vector1);
for(i=0;i<firstname.size();i++)
{
System.out.println(fnTokens);// it is printing only last record in my vector
}
}
If I print in the getTokens method itself I was able to get all records, but here only the last record.
My final intention is iterate all 3 vectors and compare the elements like vector1.getstart(),vector1.getend() and vector1.getname()
vector2.getstart(),vector2.getend() and vector2.getname()
vector3.getstart(),vector3.getend() and vector3.getname()
Can some one help me to solve this problem?
You keep overwriting the single Tokens instance you have... In your original code:
Tokens tokens=new Tokens();//create Tokens instance
while(it1.hasNext())
{
// init
while (stringTokenizer.hasMoreElements()) {
// set tokens fields
}
System.out.println(tokens);// You print the current Tokens instance
}//while(it1.hasNext()
return tokens; //only return one, at the last state.
And in the loop, you always print the current state of the Tokens instance, but return only the last.
To solve, change the method around a bit to return all instances, for example in a List:
public static List<Tokens> getTokens( Vector<NameBuffer> vc1 ) {
List<Tokens> tokenList=new ArrayList<Tokens>();//create Tokens list to return
while(it1.hasNext())
{
// init
Tokens tokens=new Tokens();//create Tokens instance inside loop
tokenList.add(tokens); //add to list to return
while (stringTokenizer.hasMoreElements()) {
// set tokens fields -- unchanged
}
System.out.println(tokens);// You print the current Tokens instance
}//while(it1.hasNext()
return tokenList; //only return the last one....
}
And then in the main method:
public static void main(String[] args) {
//...
List<Tokens> fnTokens=getTokens(vector1);
for(Tokens t: fnTokens)
{
System.out.println(t);
}
}
public static Tokens getTokens( Vector<NameBuffer> vc1 ) {
Iterator it1=vc1.iterator();
while(it1.hasNext()) {
String onerecord= it1.next().toString();
//String onerecord="start:231 stop:234 name:xyz";
String ss[]=onerecord.split(":|\\s");
System.out.println(ss[0]+" = "+ss[1]);
System.out.println(ss[2]+" = "+ss[3]);
System.out.println(ss[4]+" = "+ss[5]);
}
}
This is an extension to below question in StackOverflow as I am not understanding the accepted answer.
How do you determine the type of data contained in a string?
If someone could please give a sample code for below case:
I have a String array as below:
String[] myArray = new String[4];
myArray[0] = "one";
myArray[1] = "2012-02-25";
myArray[2] = "12345.58";
myArray[3] = "1245";
I want something as below:
for(String s:myArray){
if(s is a number){
System.out.println("A number!");
}
else if(s is a float){
System.out.println("A float!");
}
else if(s is a date){
System.out.println("A date!");
}
else if(s is a text){
System.out.println("A text!");
}
}
But I don't know what will come inside the IF conditions to determine the type of data in given String.
Thanks for reading!
The simplest way to do it is to create the aformentioned methods an simply try to parse the string like (but you have to remember that you cannot tell 100% what datatype a certain pattern is, can be multiple times at once):
public static boolean isANumber(String s) {
try {
BigDecimal d = new BigDecimal(s);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isAFloat(String s) {
//same as number, unless you want is a number to
//check if it an integer or not
try {
BigDecimal d = new BigDecimal(s);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isADate(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
sdf.parse(s);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isAText(String s) {
//everything could be considered a text
// unless you want to check that characters are within some ranges
return true;
}
public static void main(String[] args) {
String[] myArray = new String[4];
myArray[0] = "one";
myArray[1] = "2012-02-25";
myArray[2] = "12345.58";
myArray[3] = "1245";
for(String str : myArray){
if(str.matches("[\\d]+")){
System.out.println(str + " is integer");
}
else if(str.matches("[\\D]+")){
System.out.println(str + " is word");
}
else if(str.matches("[\\d.]+")){
System.out.println(str + " is double");
}
else if(str.matches("\\d{4}-\\d{2}-\\d{2}")){
System.out.println(str + " is date");
}
}
}
Output:
one is word
2012-02-25 is date
12345.58 is double
1245 is integer
One way to do it is by trying to parse the string.
Here is an example for one of the types;:
boolean isFloat(String x) {
try {
Float.parseFloat(x);
} catch (Throwable e) {
return false;
}
return true;
}
Note:
As an integer can be parsed a a float you need to test if it is an integer first.
So:
if (isInteger(s)) {
// Integer
else if (isFloat(s)) {
...
for(String s:myArray){
if(NumberUtils.isNumber(s)){ //From Apache commons
double d= Double.valueOf(s);
if (d==(int)d){
System.out.println("A number!");
}else{
System.out.println("A Float!");
}
}else if(isValidDate(s)){
System.out.println("A date!");
}else{
System.out.println("A text!");
}
}
Method for valid date check
public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
Write function like :
private boolean isFloat(String str) {
try {
Float.parseFloat(str);
return true;
} catch (NumberFormatException) {
return false;
}
}
And check the type. Or you can just use apache commons NumberUtils
There's no way of defining an array of strings with a declaration of a specific datatype. If you need something like that, use collection like List, e.g. a list of date objects. For strings, you have to programatically determine it by analyzing the data or if you already know what type of data an array of strings or a string contains in your program since you are the one who wrote it, then handle accordingly.
You can create a custom object/class which can take the value and type of data that value represents.
This program I'm making isn't compiling right, I keep getting the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9
at java.lang.String.charAt(String.java:687)
at pro1.main(pro1.java:161)
Here's my code:
import java.io.*;
import java.util.*;
public class pro1 {
static String str="";
static String str1="";
static int range=250;
static int length;
static String key="";
static String ep="";
static String pt="";
static char temp;
static int t,p,h;
static int r,x,y,z,w;
static Random generator = new Random();
static public String getContents(File aFile)
{
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
str1=contents.toString();
return str1;
}
public static void main (String args[]) throws IOException {
File testFile = new File("/home/amritha/Desktop/sam.txt");
System.out.println("Original file contents: " + getContents(testFile));
System.out.println("message:"+str1);
String sbox="abcdefghijklmnopqrstuvwxyz";
length=str1.length()-1;
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
if(t==32)
{
int t1=32;
temp=(char)t;
}
else
{
range=generator.nextInt(26)+1;
temp=sbox.charAt(range);
}
key+=""+temp;
}
System.out.println("Key:"+key);
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
{
if(t==32)
{
t=32;
temp=(char)t;
}
else
{
t-=97;
}
}
p=(int)key.charAt(i);
{
if(p==32)
{
p=32;
temp=(char)p;
}
else
{
p-=97;
}
}
if((t==32)&&(p==32))
{
int v=32;
temp=(char)v;
}
else
{
r=(t+p)%26;
temp=sbox.charAt(r);
}
ep+=""+temp;
}
System.out.println("Encrypted Text:"+ep);
for(int i=0;i<length;i++)
{
y=(int)ep.charAt(i);
{
if(y==32)
{
y=32;
temp=(char)y;
}
else
{
y-=97;
}
}
x=(int)key.charAt(i);
{
if(x==32)
{
x=32;
temp=(char)x;
}
else
{
x-=97;
}
}
if((x==32)&&(y==32))
{
int w=32;
temp=(char)w;
}
else
{
z=(y-x)%26;
temp=sbox.charAt(z);
}
pt+=""+temp;
}
System.out.println("deccrypted Text:"+pt);
}
}
Your code looks fishy in every way, and I cannot imagine anyone wanting to read 170 lines of this code.
Look at the exception: It tells you exactly what's going wrong: You pass -9 to charAt() as an index, which is - obviously - out of range, as you should only pass 0 ... (length-1) in there.
And it gives you the line number, too... so go to line number 161 and look what's in there and how it got there.
My guess would be it has something to do with this line:
z=(y-x)%26;
If x is larger than y the result of the % operation may be negative (or 0). And charAt (which is what z is given as parameter to) expects a positive value.
You should try:
z=Math.abs(y-x)%26;
Edit: As a side note, this shouldn't be to hard to figure out on your own, by looking at the exception as was pointed out by others, or in the worst case using a debugger and seeing exactly what values the different variables have and why when the exception occurs.