Below is my simple program which converts a string into elements of array, charAt(i) is not returning what it is supposed to according to documentation. My code is
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
int puz[] = new int[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (int c : puz) {
System.out.println(c);
}
}
}
Expected output: 1 2 3 4 5
Real output: 49 50 51 52 53
but when i use puz[i] = puzzle.charAt(i)-"O";
its working Fine..!
That's because a character's value is not the same as the int used to represent it. Declaring puz as a char[] should resolve the issue and print the numbers as expected.
You are displaying the character's unicode point values. Instead, you could use
System.out.println(Character.getNumericValue(c));
try
char puz[] = new char[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (char c : puz) {
System.out.println(c);
}
Its normal.
You take the string "1" not the number 1.
To get the number, prefer use Integer.paserInt(yourString);
then you'l lget your number.
As example:
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
int puz[] = new int[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = Integer.parseInt(puzzle.charAt(i));
}
for (int c : puz) {
System.out.println(c);
}
}
You're casting the char you get to an int, thus Java will print its integer representation. Store the result as an array of Strings, and loop over that array to print.
You implicitly convert char to int,a char '1' is not equals to 1,You can cast them to char like:
System.out.println((char)c);
You are using the int array so it prints the ascii values.You can do the following :
public static void fromPuzzleString(String puzzle) {
for (int i = 0; i < puzzle.length(); i++) {
System.out.println( puzzle.charAt(i));
}
}
You need not use 2 for loops and an array unnecessarily.
"charAt(i) is not returning what it is supposed to according to documentation"
You cannot put a char inside an int. Or else it will return its unicode value.
The values returned Real output: 49 50 51 52 53 are the unicode ASCII Characters codes
This will solve your issue:
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
char[] puz = new char[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (char c : puz) {
System.out.println(c);
}
}
}
However, to save memory I would suggest that you do not declare an array, display the values immediately like this:
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
for (int i = 0; i < puzzle.length(); i++) {
System.out.println(puzzle.charAt(i));
}
}
}
Related
I try to convert numbers of a String in to an array with the datatyp char. My problem is, that the number in my array is everytime 48 to high. I also know that the problem has something to do with ASCII table. What can i do to solve this problem?
package Test;
public class Main {
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber);;
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
}
use
number[indexNumber] = calculation.charAt(iNumber) - '0';
Digit 0 has an ASCII value of 48. The range of ASCII value for 0-9 digits is from 48-57. So, whenever you extract a character, let's say '5', you store 53 instead of 5 in the array. So try to use the below code modification where you subtract character '0':
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber)-'0'; //modified
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
I'm tying to learn Java. I need to make a method called reverse that gets a string and return a string (but in reverse order). Here is what i tried. Can you fix the code and explain what I'm doing wrong? Please also give me some advice about a good start in Java. Thank you!
public class Test{
public static String reverse(String a){
int j = a.length();
char[] newWord = new char[j];
for(int i=0;i<a.length();i++)
{
newWord[j] = a.charAt(i);
j--;
}
return new String(newWord);
}
public static void main(String a[]){
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
You can use this to reverse the string, you don't need to use your own method
new StringBuilder(word).reverse().toString()
If you want to use your solution you must change int j = a.length() to int j = a.length() -1;
The fixed code is
public class Test {
public static String reverse(String a) {
int j = a.length();
char[] newWord = new char[j];
for (int i = 0; i < a.length(); i++) {
newWord[--j] = a.charAt(i);
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
Like others have mentioned, arrays indexes start at 0. So if an array has size 5 for example it has indices 0,1,2,3,4. It does not have an index 5.
For an example of a string with length 5, the code change that I did newWord[--j] = a.charAt(i); will assign to the indices 4,3,2,1,0 in that order.
Regarding getting a good start in Java, I think you could try https://softwareengineering.stackexchange.com/. This site is not meant for that kind of thing.
This is a common difficulty with new Java developers.
The point you are missing is that the last entry in an array is at position a.length-1. Similarly for Strings
Here's an improved version to demonstrate.
public static String reverse(String a) {
char[] newWord = new char[a.length()];
for (int i = 0, j = a.length() - 1; i < a.length(); i++, j--) {
newWord[j] = a.charAt(i);
}
return new String(newWord);
}
You're already on the right track with your method. The one thing I will say to you is that you don't need to use an array of characters and then use something like return new String(newWord);. That's overly complicated for beginner Java in my view.
Instead, you can create an empty String and just keep appending the characters onto it as you loop through all the characters in the String you want to reverse.
So your for loop, because you're reversing the word, should begin at the end of the word being reversed (a in this case) and work backwards to index position 0 (ie. the start of the word being reversed).
Try this and see if this makes sense to you:
public static String reverse(String a) {
String reversedWord = "";
for (int index = a.length() - 1; index >= 0; index --) {
reversedWord += a.charAt(index);
}
return reversedWord;
}
This is, then, starting at the end of a, working backwards one character at a time (hence the use of index --) until we reach a point where index has gone beyond the character at index position 0 (the middle condition of index >= 0).
At each index position, we are simply taking the character from the a String and appending it onto the reversedWord String.
Hope this helps! Feel free to ask any other questions if you are stuck on this.
In your for loop, body must be as that
newWord[--j] = a.charAt(i);. It's because if the lenght of array is 8, its indexes are 0-7. So we first decrement j and then use it as array pointer.
public class Test {
public static String reverse(String a) {
int size= a.length();//size of string
char[] newWord = new char[size];//intialize
for (int i = size-1,j=0; i >=0 ; i--,j++) {//loop start from 7 to 0
newWord[j] = a.charAt(i);// and reverse string goes from 0 to 7
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
static void reverse {
String word = "Hello World";
StringBuilder str = new StringBuilder(word);
str.reverse();
System.out.println(str);
}
or you could do
new StringBuilder(word).reverse().toString()
public static void main(String[] args) {
String input = "hello world";
String output = new String();
for (int i = input.length() - 1; i >= 0; i--) {
output = output + input.charAt(i);
}
System.out.println(output);
}
package Reverse;
import java.util.*;
public class StringReverse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a String: ");
String original = input.nextLine();
String rev = "";// Initialize as Empty String
for(int i = original.length() - 1 ; i>=0 ; i--){
rev += original.charAt(i);
}
System.out.println("Reverse form: "+rev);
}
}
When converting an integer to int array, for example 123 to {1,2,3}, I am getting values {49,50,51}.
Not able to find what is wrong with my code.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
Output:
49
50
51
charAt(i) will give you UTF-16 code unit value of the integer for example in your case, UTF-16 code unit value of 1 is 49.
To get integer representation of the value, you can subtract '0'(UTF-16 code unit value 48) from i.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i - '0');
}
}
}
Output:
1
2
3
To add a little Java 8 niceties to the mix which allows us to pack everything up neatly, you can optionally do:
int i = 123;
int[] nums = Arrays.stream(String.valueOf(i).split(""))
.mapToInt(Integer::parseInt)
.toArray();
Here we get a stream to an array of strings created by splitting the string value of the given integer's numbers. We then map those into integer values with Integer#parseInt into an IntStream and then finally make that into an array.
temp.charAt(i) is basically returning you characters. You need to extract the Integer value out of it.
You can use:
newGuess[i] = Character.getNumericValue(temp.charAt(i));
Output
1
2
3
Code
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = Character.getNumericValue(temp.charAt(i));
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
As your interest is to get as an integer value of an string. Use the method parse int Integer.parseInt() . this will return as integer.
Example :
int x =Integer.parseInt("6"); It will return integer 6.
I have to write a scrabble code in java without the use of if/switch statements. this is what i have so far
public class Scrabble {
public static void main(String[] args) {
}
public static int computeScore(String word) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int[] values = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,3,3,10,1,1,1,1,4,4,8,4,10};
int sum = 0;
for(int i = 0; i <word.length();i++) {
????
}
return sum;
}
}
I need some help, I had the idea of finding the character inside the string and finding its value but not sure how to write it out. Any help will be great! Thanks!
Inside you for loop you would need to do the following:
sum += values[aplphabet.indexOf(word.charAt(i))];
So your loop should so something like:
for(int i = 0; i <word.length();i++) {
sum += values[aplphabet.indexOf(word.charAt(i))];
}
This will of course not handle any modifier tiles on the scrabble board.
Alternatively you can use a HashMap<char, int> to store your letters, so that accessing them is a bit easier:
public class Scrabble {
HashMap<char, int> alphabet;
public static void main(String[] args) {
//initialize the alphabet and store all the values
alphabet = new HashMap<char, int>();
alpahbet.put('A', 1);
alpahbet.put('B', 3);
alpahbet.put('C', 3);
//...
alpahbet.put('Z', 10);
}
public static int computeScore(String word) {
int sum = 0;
for(int i = 0; i <word.length();i++) {
//look up the current char in the alphabet and add it's value to sum
sum += alphabet.get(word.charAt(i));
}
return sum;
}
}
String database[] = {'a', 'b', 'c'};
I would like to generate the following strings sequence, based on given database.
a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
...
I can only think of a pretty "dummy" solution.
public class JavaApplication21 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
String query = "a";
StringBuilder query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
query = query_sb.toString();
System.out.println(query);
}
query = "aa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
query = query_sb.toString();
System.out.println(query);
}
}
query = "aaa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
for (int c = 0; c < database.length; c++) {
query_sb.setCharAt(2, database[c]);
query = query_sb.toString();
System.out.println(query);
}
}
}
}
}
The solution is pretty dumb. It is not scale-able in the sense that
What if I increase the size of database?
What if my final targeted print String length need to be N?
Is there any smart code, which can generate scale-able permutation and combination string in a really smart way?
You should check this answer: Getting every possible permutation of a string or combination including repeated characters in Java
To get this code:
public static String[] getAllLists(String[] elements, int lengthOfList)
{
//lists of length 1 are just the original elements
if(lengthOfList == 1) return elements;
else {
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
//append the sublists to each element
int arrayIndex = 0;
for(int i = 0; i < elements.length; i++){
for(int j = 0; j < allSublists.length; j++){
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}
return allLists;
}
}
public static void main(String[] args){
String[] database = {"a","b","c"};
for(int i=1; i<=database.length; i++){
String[] result = getAllLists(database, i);
for(int j=0; j<result.length; j++){
System.out.println(result[j]);
}
}
}
Although further improvement in memory could be made, since this solution generates all solution to memory first (the array), before we can print it. But the idea is the same, which is to use recursive algorithm.
This smells like counting in binary:
001
010
011
100
101
...
My first instinct would be to use a binary counter as a "bitmap" of characters to generate those the possible values. However, there are several wonderful answer to related questions here that suggest using recursion. See
How do I make this combinations/permutations method recursive?
Find out all combinations and permutations - Java
java string permutations and combinations lookup
http://www.programmerinterview.com/index.php/recursion/permutations-of-a-string/
Java implementation of your permutation generator:-
public class Permutations {
public static void permGen(char[] s,int i,int k,char[] buff) {
if(i<k) {
for(int j=0;j<s.length;j++) {
buff[i] = s[j];
permGen(s,i+1,k,buff);
}
}
else {
System.out.println(String.valueOf(buff));
}
}
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
char[] buff = new char[database.length];
int k = database.length;
for(int i=1;i<=k;i++) {
permGen(database,0,i,buff);
}
}
}
Ok, so the best solution to permutations is recursion. Say you had n different letters in the string. That would produce n sub problems, one for each set of permutations starting with each unique letter. Create a method permutationsWithPrefix(String thePrefix, String theString) which will solve these individual problems. Create another method listPermutations(String theString) a implementation would be something like
void permutationsWithPrefix(String thePrefix, String theString) {
if ( !theString.length ) println(thePrefix + theString);
for(int i = 0; i < theString.length; i ++ ) {
char c = theString.charAt(i);
String workingOn = theString.subString(0, i) + theString.subString(i+1);
permutationsWithPrefix(prefix + c, workingOn);
}
}
void listPermutations(String theString) {
permutationsWithPrefix("", theString);
}
i came across this question as one of the interview question. Following is the solution that i have implemented for this problem using recursion.
public class PasswordCracker {
private List<String> doComputations(String inputString) {
List<String> totalList = new ArrayList<String>();
for (int i = 1; i <= inputString.length(); i++) {
totalList.addAll(getCombinationsPerLength(inputString, i));
}
return totalList;
}
private ArrayList<String> getCombinationsPerLength(
String inputString, int i) {
ArrayList<String> combinations = new ArrayList<String>();
if (i == 1) {
char [] charArray = inputString.toCharArray();
for (int j = 0; j < charArray.length; j++) {
combinations.add(((Character)charArray[j]).toString());
}
return combinations;
}
for (int j = 0; j < inputString.length(); j++) {
ArrayList<String> combs = getCombinationsPerLength(inputString, i-1);
for (String string : combs) {
combinations.add(inputString.charAt(j) + string);
}
}
return combinations;
}
public static void main(String args[]) {
String testString = "abc";
PasswordCracker crackerTest = new PasswordCracker();
System.out.println(crackerTest.doComputations(testString));
}
}
For anyone looking for non-recursive options, here is a sample for numeric permutations (can easily be adapted to char. numberOfAgents is the number of columns and the set of numbers is 0 to numberOfActions:
int numberOfAgents=5;
int numberOfActions = 8;
byte[][]combinations = new byte[(int)Math.pow(numberOfActions,numberOfAgents)][numberOfAgents];
// do each column separately
for (byte j = 0; j < numberOfAgents; j++) {
// for this column, repeat each option in the set 'reps' times
int reps = (int) Math.pow(numberOfActions, j);
// for each column, repeat the whole set of options until we reach the end
int counter=0;
while(counter<combinations.length) {
// for each option
for (byte i = 0; i < numberOfActions; i++) {
// save each option 'reps' times
for (int k = 0; k < reps; k++)
combinations[counter + i * reps + k][j] = i;
}
// increase counter by 'reps' times amount of actions
counter+=reps*numberOfActions;
}
}
// print
for(byte[] setOfActions : combinations) {
for (byte b : setOfActions)
System.out.print(b);
System.out.println();
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
import java.util.*;
public class Permutation {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("ENTER A STRING");
Set<String> se=find(in.nextLine());
System.out.println((se));
}
public static Set<String> find(String s)
{
Set<String> ss=new HashSet<String>();
if(s==null)
{
return null;
}
if(s.length()==0)
{
ss.add("");
}
else
{
char c=s.charAt(0);
String st=s.substring(1);
Set<String> qq=find(st);
for(String str:qq)
{
for(int i=0;i<=str.length();i++)
{
ss.add(comb(str,c,i));
}
}
}
return ss;
}
public static String comb(String s,char c,int i)
{
String start=s.substring(0,i);
String end=s.substring(i);
return start+c+end;
}
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!