I've almost got it except when I run the program it parses all but the first letter of the string Hello World: "e l l o w o r l d." Heres my code; what am I missing?
import java.util.Scanner;
public class encodeTesting {
public static void main(String []Args){
//Scanner scan = new Scanner (System.in);
String x = "Hello World "; //TEST STRING
//System.out.println(x.length()); //Console log test
char[] y = new char[x.length()]; // Array Y
//Defining Variables:
int i;
int z = 0;
int a = 1;
while(a<x.length()){ //should repeat as many times as needed to parse String X
//Parse Algorithm follows:
y[z] = x.charAt(x.length() - a);
System.out.println(y[z]);
z = z + 1;
a = a + 1;
}
}
public static void main(String[] Args) {
String x = "Hello World ";
char[] y = new char[x.length()];
int i;
int z = 0;
int a = 1;
while (a <= x.length()) {
y[z] = x.charAt(x.length() - a);
System.out.println(y[z]);
z = z + 1;
a = a + 1;
}
}
You need to use:
while (a <=x.length())
So that when x.charAt(x.length() - a); evaluates at x.charAt(0); getting the first character of the string.
You could make this simple and do a basic for loop.
public static void main(String[] Args){
String x = "Hello World ";
int length = x.length();
char[] y = new char[length];
for(int i = 0; i < length; i++){
y[i] = x.charAt(length - i - 1);
System.out.println(y[i]);
}
}
If you want to do something for each character in your string, this is the way to do it:
public static void main (String[] args){
String test = "Hello world";
for(char c: test.toCharArray()) {
//do your operations here
System.out.print(c);
}
}
//Output: Hello World
Read the for-loop as "for each character in test"
By the looks of it you just want to convert your string to a character array, in which case just use this:
String myStringVariable = "abc";
char[] stringAsArray = myStringVariable.toCharArray();
Or you can even do it like this:
char[] stringAsArray = "Hello world".toCharArray();
Related
I have a string "Hello, World!" that I have to convert into a char array. I then found the index of the char ',' - to which I want to create a new char array that contains " World!, Hello".
I've got the first index of the char array moved to the back - such that it prints out "ello, World!H".
How can I use my variable indexDelimiter to move the rest of the char arrays (as well as the ',') to the back? I've been looking at this problem forever, and I'm very confused as to how I could go about this.
I can't use ListArray. I has to be an Array.
public class ArrayTest {
public static void main(String[] args) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
for (int i = 0; i < oldCharArray.length - 1; i++) {
newCharArray[i] = oldCharArray[i + 1];
}
newCharArray[oldCharArray.length - 1] = oldCharArray[0];
for (int i = 0; i < newCharArray.length; i++) {
System.out.print(newCharArray[i]);
}
// This prints out "ello, World!H" but I want " World!, Hello"
}
}
This code will produce "World!,Hello", take a look and see if it meets your needs.
public static void main(String args[]) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
int i = 0;
for (i = 0; i < oldCharArray.length-indexDelimiter-1; i++) {
newCharArray[i] = oldCharArray[indexDelimiter + i + 1];
}
newCharArray[i] = delimiter;
i++;
int j = i;
while (i < oldCharArray.length) {
newCharArray[i] = oldCharArray[i - j];
i++;
}
System.out.println(newCharArray);
}
If you mean backward, you can reverse the by splitting it first
public char[] reverse_comma_split(String str) {
String[] spl = str.split(",");
String reversed = new String();
for (int i = spl.length - 1; i >= 0; i--) {
reversed += spl[i];
if (i != 0)
reversed += ", ";
}
return reversed.toCharArray();
}
Calling reverse_comma_split("Hello, world!") would return a char array of " world!, Hello"
However, if you insist to get uppercase char in every split, you can modify the loop in which spl[i] to spl[i].substring(0, 1).toUpperCase() + spl[i].substring(1)
I am pretty sure indexOf is suppose to print out the number the letter is located! And in my code if it is there is should add to result to see how many "x" are in message! Although it dosen't work it print out 7 meaning it completely ignores my if statement!
public class Test1
{
public static void main(String[] args)
{
String message = "xyxxzax";
int result = 0;
int y = message.length();
for(int x = 0 ; y > x; x++){
String v = message.substring(x,x+1);
if (message.indexOf("x") > -1){
result++;
}
}
System.out.println(result);
}
}
That is because you never change the string message! And I suppose you that this is not how indexOf works. So:
public class Test1
{
public static void main(String[] args)
{
String message = "xyxxzax";
int result = 0;
int y = message.length();
for(int x = 0 ; y > x; x++){
String v = message.substring(x,x+1);
if (v.equals("x")){
result++;
}
}
System.out.println(result);
}
}
Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
How do i make an array with the opposite letters of the first array im making? For example if the string is "Hello", i want to use arrays to print out "olleH". When i try to return the variables it tells me "String index out of range: -1". Can anyone please tell me why? This is my code so far:
public class april{
public static void main(String [] args){
System.out.println("What do you want backwards?");
System.out.println("Your new word is " + reverse(IO.readString()));
}
public static String reverse(String original){
char [] letters = new char [original.length()];
char [] opp = new char [original.length()];
char c= 'a';
char d= 'a';
String word= " ";
String opposite= " ";
for (int x=0;x<original.length();x++){
c = original.charAt(x);
letters[x]= c;
if (x!=0){
d = original.charAt(-x-1);
opp[-x]=d;
}
else if (x==0){
d = original.charAt(-1);
opp[x]= d;
}
word += letters[x];
opposite += opp[x];
}
return word;
return opposite;
You're close! You just need to start at the other end of the String for the second array (with proper syntax):
for (int x = 0; x < original.length(); x++) {
char c = original.charAt(x);
char d = original.charAt(original.length() - x - 1);
letters[x] = c;
opp[original.length() - x - 1] = d;
}
Note: You also have to subtract 1 because both arrays and string indices are 0-indexed.
I think this is a great way to do it.
public class Main {
public static void main(String[] args) {
String reversed = reverse("Hello");
System.out.println(reversed);
}
private static String reverse(String word) {
byte[] array = word.getBytes();
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
return new String(array);
}
}
Your method receives a String and returns another String, so you don't need to work with arrays at all, just use the reverse method of the StringBuilder class.
public static String reverse(String original) {
return new StringBuilder(original).reverse().toString();
}
Given a equation :
433+4H8= 871
H can be anyside of equation. Find the value of H and replace it in given equation.
The output should be :
433+438=871
I have tried the following code but conversion of string to int does not work...
import java.util.Scanner;
import java.io.*;
class hole
{
public static void main(String[] args)
{
Scanner reader= new Scanner(System.in);
int[] nums= new int[3];
String str= reader.nextLine();
String str_1= str.replaceAll("=","+");
String[] split= str_1.split("[+]");
for (int k=0; k<split.length; k++)
{
String ex= split[k];
nums[k]= Integer.parseInt(ex);
}
}
}
4H8 isn't an integer, so parseInt won't work on it.
It seems like you still have a bit of a way to go on this, so I won't spoil your fun by giving you the code, just some ideas.
Assuming the equation is always X + Y = Z, which X, Y and Z being some integers, one of which can contain an H...
You need to have a couple of cases:
If the H is in X, you can get X by subtracting Y from Z.
If the H is in Y, you can get Y by subtracting X from Z.
If the H is in Z, you can get Z by adding X and Y.
But this still doesn't give you H. For this, you can simply find the position of the H in the string we have and extract the digit at that position in the number calculated above.
So before calling parseInt, you should look for the H and simply store the string instead if you find it.
parseInt also doesn't like spaces, so you should remove those in some way or another.
If equations aren't always in the form X + Y = Z (i.e. you can also have subtraction, multiplication, division and/or multiple terms), it gets a bit more complicated.
Why would you not just subtract the final answer minus the first number and build the third number. Splitting the string is redundant as you can just use simple math to solve for x.
871-433 = 438
h=3
public static void main(String[] args)
{
int a = 433;
int b = 871;
int c = b - a;
String s = "4H8";
char x;
int location = 0;
for(int i = 0; i < s.length(); i++)
{
char d = s.charAt(i);
if(d.isDigit()){
}
else{
location = i;
x = d;
}
}
String solve = c.toString();
System.out.println(x + "=" + solve.charAt(location) );
}
Try this (comments are self explanatory):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
int varIndex = 0;
int result = 0;
String str = reader.nextLine();
//remove spaces and split into 3 parts based on symbols
String[] components = str.replaceAll(" ", "").split("\\+|=");
for (int i = 0; i < components.length; i++) {
try {
nums[i] = Integer.parseInt(components[i]);
} catch (Exception e) {
varIndex = i; //this component contains "H"
}
}
//Calculate the value of the number which has "H"
switch (varIndex) {
case 0:
result = nums[2] - nums[1]; break;
case 1:
result = nums[2] - nums[0]; break;
case 2:
result = nums[0] + nums[1]; break;
}
nums[varIndex] = result;
//Print the output
System.out.println(nums[0] + " + " + nums[1] + " = " + nums[2]);
System.out.println("H = " + (String.valueOf(result)).charAt(components[varIndex].indexOf('H')));
}
Try below program , This works only for input a+b=c format
Below program is giving correct output
import java.util.Scanner;
public class Hole {
public static void main(String args[])
{
int hLocation = 0;
int result;
char hValue;
Scanner in=new Scanner(System.in);
String str=in.nextLine().replaceAll(" ", "");
String[] split= str.split("[+=]");
for(int i=0;i<split.length;i++){
if(split[i].contains("H")){
hLocation=i;
}
}
if(hLocation==0){
result=Integer.parseInt(split[2])-Integer.parseInt(split[1]);
}else if(hLocation==1){
result=Integer.parseInt(split[2])-Integer.parseInt(split[0]);
}
else{
result=Integer.parseInt(split[0])+Integer.parseInt(split[1]);
}
hValue= String.valueOf(result).charAt(1);
str=str.replace('H', hValue);
System.out.println(str);
}
}
Try this:
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
boolean[] isNum = new boolean[3];
String str = reader.nextLine();
// String str_1= str.replaceAll("=","+");
String[] split = str.split("[+=]");
int i = 0;
for (int k = 0; k < split.length; k++) {
try {
String s = split[k];
isNum[k] = true;
nums[i] = Integer.parseInt(s);i++;
} catch (NumberFormatException e) {
// TODO: handle exception
isNum[k] = false;
}
}
int tot ;
if(str.indexOf("H")>str.indexOf("=")){
tot = nums[1] + nums[0];
}else{
tot = nums[1] - nums[0];
}
for (int k = 0; k < split.length; k++) {
if(!isNum[k]){
int indx = split[k].indexOf("H");
String h = Integer.toString(tot).charAt(indx)+"";
h = str.replace("H",h);
System.out.println("New expression :"+h);
}
}
}