Alright, I want to make a method for my Chemistry game/project where it would:
take a String
then it would take the String, check for numbers, and if there are numbers, turn it into a subscript of that same number.
return the updated String
My original thoughts was to turn the string into a char array, then make a for loop where I try Integer.parseInt(Character.toString(char array element)), and if it threw a NumberFormatException it would continue the for loop. If it didn't throw an error, then I retain that number, add it to 2080 (because \u2080 -> \u2089 are the subscript unicodes) and then somehow smush that number back into a char.
I tried to write the code for it, but wasn't sure how to proceed.
private String processName(String original)
{
char[] or = original.toCharArray();
int returned = 0;
for(char character : or)
{
try
{
returned = Integer.parseInt(Character.toString(character));
}
catch (Exception e)
{
continue;
}
if(returned != 0)
{
returned += 2080;
String temp = "\\u" + returned;
//gave up here
}
}
}
You're almost there. Remember that chars are two bytes, so they can hold the values you want:
for(int i = 0; i < or.length; i++)
{
try
{
returned = Integer.parseInt(Character.toString(or[i]));
}
catch (Exception e)
{
continue;
}
if(returned != 0)
{
or[i] = (char) (returned + 2080);
}
}
You could get rid of some of the cost of converting to an int by simply checking if the char is a digit and, if it is, adding the appropriate amount, but since this code already works I'll leave that up to you.
Related
My problem is that I need to identify characters which differ between the two given strings in a visually striking way. Output the two input strings on two lines, and then identify the differences on the line below using periods (for identical characters) and asterisks (for differing characters). For example:
ATCCGCTTAGAGGGATT
GTCCGTTTAGAAGGTTT
*....*.....*..*..
I have tried to write two string with each other but I dont know how to make the program check for every character in the string and see if those match
This is what I have done so far :/
System.out.println("String 1: ");
String var1 = Scanner.nextLine();
System.out.println("String 2: ");
String var2 = Scanner.nextLine();
if (same (var1, var2))
System.out.println(".........");
else
System.out.println("********");
public static boolean same (String var1, String var2){
if (var1.equals(var2))
{
return true;
}
else
{
return false;
}
Can anyone help me with this?
You need to loop through your Strings and compare characters one by one. To run through your list you can make a for-loop. Use an int as counter and use the method length() to obtain your string size.
for(int i=0; i<string1.length(); i++ {
// do stuff
}
Then since you have a counter going through all position of your string, you can obtain the character at a specific position in this string using the method charAt()
char char1 = string1.charAt(i);
Then compare the character to check if they are the same. If they are print a dot . if they're not print an asterisk *
if(char1 == char2) {
System.out.print(".");
} else {
System.out.print("*");
}
In the above part I supposed your two string have the same size. If it's not the case, you can first determine which one is the smallest (and so which is the biggest) :
String smallestString;
String biggestString;
if(string1.size() > string2.sise()) {
smallestString = string2;
biggestString = string1;
else {
smallestString = string1;
biggestString = string2;
}
Then make your for loop go through the smallest String, otherwise you will face IndexOutOfBoundsException.
for(int i=0; i<smallestString.length(); i++ {
// do stuff
}
And the end of this for loop print asterisks for the characters that left in the biggest String
for(int j=smallestString.length(); j<biggestString.length(); j++) {
System.out.print("*");
}
This is what I've come up with.Mind you there are better ways to do this and I've just written it with as much effort as you put in your question.
public class AskBetterQuestion{
public static void main(String[] args) {
// TODO Auto-generated method stub
String w1="ATCCGCTTAGAGGGATT";
String w2="GTCCGTTTAGAAGGTTT";
char[] first = w1.toCharArray();
char[] second = w2.toCharArray();
int minLength = Math.min(first.length, second.length);
char[] out=new char[minLength];
for(int i = 0; i < minLength; i++)
{
if (first[i] != second[i])
{
out[i]='.';
}
else out[i]='*';
}
System.out.println(w1);
System.out.println(w2);
System.out.print(out);
}
}
public char[] Cache_1(int word_address,int cache_set,int ls,char[] s1)
{
char cache_1[][] = new char[32][4];
char s0[] = new char[32];
InterConnectionNetwork ic = new InterConnectionNetwork();
if(ls == '0') {
if((cache_1[cache_set][0]) == '1') { // Check Valid Bit and transfer content
// if valid bit is high
for(int i=0;i<32;i++) { // Load
s0[i] = cache_1[cache_set][i];
}
} else { // Valid bit low
s0 = ic.determinenode(word_address);
}
return s0;
} else {
if((cache_1[cache_set][0]) == '1') {
for(int i=0;i<32;i++) {
cache_1[cache_set][i] = s0[i];
}
} else
cache_1[cache_set][] = ic.determinenode(word_address); //returns char[]
return (cache_1[cache_set][]); //Problem here
}
}
This is a chunk from the code that I am writing. The problem here is that return type being used is char[] and cache_1[cache_set][] is actually equivalent to single character array, but it is showing an error. Please help me to resolve it.
You should return cache_1[cache_set], not cache_1[cache_set][].
You defined return type as
char[]
which means char array (linear)
and you are returning
cache_1[cache_set][] //should give multiple error and one for not giving index inside the second [?]
if you write this correctly then you are returning an char not char[]
You have to change any one of it.
This is a homework assignment.
I am prompting the user to input any amount of numbers, followed by a word. Because I do not know the amount of numbers that will be input, I am storing them in a String[], then moving them to an ArrayList.
I am storing the input correctly into the String[] by splitting the scanner input at white spaces.
Now I am attempting to add the contents of a String[] into an ArrayList with the following:
int i = 0;
for ( i = 0; i < inputToStringArray.length; i++) {
if(values.add(Double.parseDouble(inputToStringArray[i]))){ //if you can parse a double, parse a double
values.add(Double.parseDouble(inputToStringArray[i]));
}
}
Because I do not want the word at the end of the input, I am parsing the String[] for doubles.
Problem is, the ArrayList copies each number, storing it twice consecutively.
An input of 1, 2.2, 3.3 will store as 1.0, 1.0, 2.2, 2.2, 3.3, 3.3.
Why?
Basically, if List#add returns true, you're adding it again...
if(values.add(Double.parseDouble(inputToStringArray[i]))){ //if you can parse a double, parse a double
values.add(Double.parseDouble(inputToStringArray[i]));
}
Which basically says...
if add(value) {
add(value) // again...
}
Something like...
for ( i = 0; i < inputToStringArray.length; i++) {
try {
values.add(Double.parseDouble(inputToStringArray[i]));
} catch (NumberFormatException exp) {
System.err.println(inputToStringArray[i] + " is not a valid double");
}
}
May work better...
Because you are adding it twice! Your If statement is attempting to add it to values, then if it succeeds, you are adding it again.
Try something like this:
int i = 0;
for ( i = 0; i < inputToStringArray.length; i++) {
try {
values.add(Double.parseDouble(inputToStringArray[i]));
} catch (NumberFormatException e) {
// not a number!
e.printStackTrace();
}
}
a) In fact you call the method values.add() twice (you don't need it on the if clause).
b) You may encounter an exception if the string value is not a number, you should catch this
You should use something like this:
for ( int i = 0; i < inputToStringArray.length; i++) {
try {
values.add(Double.parseDouble(inputToStringArray[i]));
} catch (NumberFormatException e){}
}
in java,
is it possible to check a string has special characters or letters on it and if so throw an exception?
something like this but using try/catch
/** Get and Checks if the ssn is valid or not **/
private String getSSN(){
String tempSSN;
tempSSN = scan.nextLine();
if(tempSSN.matches("^.*[^a-zA-Z ]{9}.*$") == false){
System.out.print("enter a valid SSN without spaces or dashes.");
tempSSN= scan.nextLine();
}
return tempSSN;
}
If you can do it without exception handling, there is no obvious reason for why you would use a try-catch block. But if you want to throw an exception, it's not a must to use a try-catch block. You can use throw.
if(something) {
throw new SomeAppropriateException("Something is wrong");
}
You can use a catch block if you want to catch an exception and log any error or message and continue the execution. Or you catch an exception when you want to throw other meaningful exception.
I would import the characters into an array of characters then use a loop to check each character for the character types that you want to throw the exception for.
Some sudo code below:
private String getSSN(){
String tempSSN = scan.nextLine();
try {
char a[] = tempSSN.toCharArray();
for (int i = 0; i < a.length(); i++) {
if(a[i] != ^numbers 0 - 9^) { //sudo code here. I assume you want numbers only.
throw new exceptionHere("error message"); // use this to aviod using a catch. Rest of code in block will not run if exception is thrown.
}
catch (exceptionHere) { // runs if exception found in try block
System.out.print("enter a valid SSN without spaces or dashes.");
tempSSN= scan.nextLine();
}
return tempSSN;
}
I would also consider running an if on the array not being 9 characters in length. I assume you are trying to capture ssn's which are always 9 characters.
if (a.length != 9) {
throw ....
}
You can do this without the try/catch. And the above will break if they enter an invalid ssn a second time.
private String getSSN(){
String tempSSN = scan.nextLine();
char a[] = tempSSN.toCharArray();
boolean marker;
for (int i = 0; i < a.length(); i++) {
if(a[i] != ^numbers 0 - 9^) { //sudo code here. I assume you want numbers only.
boolean marker = false;
}
while (marker == false) {
System.out.print("enter a valid SSN without spaces or dashes.");
tempSSN = scan.nextLine();
for (int i = 0; i < a.length(); i++) {
if(a[i] != ^numbers 0 - 9^) { //sudo code here. I assume you want numbers only.
marker = false;
else
marker = true;
}
}
return tempSSN;
}
You can optionally use the contains method in some way I am sure.
boolean marker = tempSSN.contains(i.toString()); // put this in the for loop and loop so long as i < 10; this will go 0 - 9 and check them all.
String[] tokens = s.split(' ');
for(int i = 0; i < (tokens.length) - 1; ++i)
{
if(isDigit(tokens[i]))
{
// Two numbers cannot be together without an operator.
if(isDigit(tokens[i + 1]))
{
check = 1;
break;
}
if((tokens[i + 1] == '(') )
{
check = 1;
break;
}
}
}
s is the string i'm splitting. after splitting i want to check whether each split part is a digit. i m not able to use isDigit because it can only be used on characters and here the split part is String.
NOTE: i m writing a program for a calculator. if i use toCharArray() the more than one digit numbers will be split. eg. 23 will become 2 and 3 seperately.
int isDigit = false;
try
{
Integer.parseInt(tokens[i])
isDigit = true;
}
catch(NumberFormatException e)
{
}
YOu might use Integer.parseInt(...) if your number should be Integer (same for other types). It throws NumberFormatException on invalid number I believe.
try{
if(isDigit(Integer.parseInt(tokens[i]))
{
//Will come here if it is an integer
}
} catch(NumberFormatException nfe) {
//Will come here if it is not an integer
}
Do you want to know if every token is a number?
try{
Integer.parseInt(token)
return true;
} catch (numberFormatException){
return false;
}
or use apache commons lang http://commons.apache.org/lang/api-release/index.html
StringUtils.isNumeric()
You may want to use string.toCharArray() method instead of string.split(), it produces an array of chars that can then be checked using Character.isDigit(char) method. Hope this helps.
One way: use Integer.parse(token) and catch NumberFormatException for the ones that aren't numbers:
Or use token.toCharArray() and test the characters individually.