I'm creating a very simple encoder that will shuffle the characters in a string. I've written it to split this string in half, forming two new variables. The user chooses the number of shuffles they want and that is passed as a parameter in the new class constructor -- which should then use that shuffle value throughout the class. Mine is not. The shuffleEncryption method is using the class variable, 0, instead. I know this must be something very obvious, but I am not catching it. :/
//From Main Class
System.out.println("Enter message to encrypt: ");
String message = input.next();
System.out.print("Number of shuffles: " );
int numShuffles = input.nextInt();
ShuffleCipher shuffle = new ShuffleCipher(numShuffles);
System.out.println(shuffle.encode(message));
//The shuffle class
public class ShuffleCipher implements MessageEncoder {
int shuffle;
public ShuffleCipher(int shuffle) {
shuffle = this.shuffle;
}
private String shuffleEncryption(String str) {
int middle = str.length()/2;
int loop = 1;
System.out.println("shift" + shuffle);
StringBuilder sb = new StringBuilder();
do {
String firstHalf = str.substring(0, middle);
System.out.println("first:" + firstHalf);
String secondHalf = str.substring(middle);
System.out.println("second:" + secondHalf);
for(int i = 0, j = 0; i < firstHalf.length(); i++, j++) {
sb = sb.append(secondHalf.charAt(i));
if(j < secondHalf.length()) {
sb = sb.append(firstHalf.charAt(i));
}
str = sb.toString();
}
loop++;
} while (loop <= shuffle);
return str;
}
#Override
public String encode(String plainText) {
String shuffled;
shuffled = shuffleEncryption(plainText);
return shuffled;
}
}
You are not setting the shuffle member variable in the constructor.
Change this:-
public ShuffleCipher(int shuffle) {
shuffle = this.shuffle;
}
to this:-
public ShuffleCipher(int shuffle) {
this.shuffle = shuffle;
}
Related
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();
I'm am trying to update a code that I have previously written to "rotate a String." Currently my program accepts a string from keyboard input and an integer n. ex. "abcdefg", 3. Then rotates the string by n characters before returning the rotated string i.e. "efgabcd". Now for the tricky part. I'm trying to update this to do essentially the same thing but with a sentence. So the inputs would be a something like "This is an example" and an integer 3. then the output would be "is an example this." I assume splitting the sentence into an array would be my best bet; however my unfamiliarity with strings doesn't allow my to know how to go about doing this.
import java.util.*;
public class Rotate
{
public static String rotate(String s, int num)
{
int length = s.length();
String a = s.substring(0,(length-num));
String b = s.substring((length-num),length);
String c = b + a;
return c;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a string:");
String s = input.nextLine();
System.out.print("Enter the number of characters that you want to rotated to right:");
int n =input.nextInt();
String t = rotate(s, n);
System.out.println("The rotated string is "+ t);
}
}
Here's a sample solution:
int num = 3;
String str = "This is a test";
String[] strArr = str.split(" ");
int length = strArr.length;
String[] temp = Arrays.copyOfRange(strArr, length - num, length);
System.arraycopy(strArr, 0, strArr, num, length - num);
System.arraycopy(temp, 0, strArr, 0, temp.length);
str = String.join(" ", strArr);
str now contains "is a test This".
EDIT: Fixed to rotate to right.
I actually prefer #fergDEV's solution, but it can be cleaned up a bit if you're using Java 8:
int num = 3;
String str = "This is a test";
List<String> parts = Arrays.asList(str.split(" "));
Collections.rotate(parts, 3);
String.join(" ", parts);
The Collections utils are your friend :P.
public class Main {
public static String rotateSetence(final String input, final int rotation) {
final List<String> results = Arrays.asList(input.split(" "));
Collections.rotate(results, rotation);
final StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
outputBuilder.append(results.get(i));
if (i != results.size() - 1)
outputBuilder.append(" ");
}
return outputBuilder.toString();
}
public static void main(String[] args) {
final String inputString = "This is an example";
final int sentenceRotation = 3;
final String expectedResult = "is an example This";
final String result = rotateSetence(inputString, sentenceRotation);
System.out.println("result " + result);
if (result.equals(expectedResult)) {
System.out.println("Passed");
} else {
System.out.println("Failed");
}
}
}
EDIT
The builder code can be replaced with string.join ... thanks to #shmosel.
final StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
outputBuilder.append(results.get(i));
if (i != results.size() - 1)
outputBuilder.append(" ");
}
return outputBuilder.toString();
can be replaced with
return String.join(" ", results);
You can also make use of two for loops, such that in the first for loop you loop from num (provided by user) position to the end of the string. And in the second loop you loop from start of string until the position of num.
For above logic to work, you obviously need to split your string using space into array of strings. See below:
public static String rotate(String s, int num)
{
//split the sentence by space
String[] chunks = s.split(" ");
//use StringBuilder to build rotated string
StringBuilder builder = new StringBuilder();
//loop from position specified by user to end of array
for(int i = num; i < chunks.length; i++) {
builder.append(chunks[i] + " ");
}
//loop from start of array to position specified by user
for(int i = 0; i < num; i++) {
builder.append(chunks[i] + " ");
}
return builder.toString();
}
The input and output is shown below:
Enter a string:My name is Raf and I am super super fun guy trust me
Enter the number of characters that you want to rotated to right:2
The rotated string is : is Raf and I am super super fun guy trust me My name
From my current code how would i print the array{10,20,30,40,50,60,70,88,99,100} using a method display and calling it using System.out.println(myobject.display()) in my main.
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(){
String str = "";
for(int i = 0; i < 10; i++){
str= str+ " ";
}//for
return str;
}//display
My current method display does not display anything.
public TestA()
{
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
System.out.println(display(iA));
}
public static String display(int[] myData)
{
String str = "";
for(int i = 0; i < myData.length; i++){
str += myData[i]+ " ";
}
return str;
}
You need to call the method and print the result. Also use the array iA in your method.
System.out.println(display());
Your for loop is just adding an empty string to an empty string 10 times. You are never adding in the text from your array based on the index i. During your loop, you should be adding the space as well as the value at the current array position.
Your method display() is indeed doing something. It is returning 10 spaces, which are being printed out in your main method. You need to actually use the array at some point. Try something like:
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(int[] iA){
String str = "";
for(int i = 0; i < 10; i++){
str= str + Integer.toString(iA[i]) + " ";
}//for
return str;
}//display
My main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf("First integer: %s \n", firstInt.display());
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result = "";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
You did not instantiate your array. You need something like:
private int[] intArray = new int[SIZE];
where size is the length of your array.
You are not initialize the array intArray, that way you are getting error, here is the complete program
import java.util.Scanner;
class TestForNull {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf ("First integer: %s \n", firstInt.display());
}
}
and this is LargeInteger
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
private int[] intArray;
Member variables are null by default, so you need to initialize this.
Most likely you want it the same size as your string:
public LargeInteger(String s) {
intArray = new int[s.length()]; // Create the actual array before you try to put anything in it
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
Or you should use a container that resizes itself, like ArrayList.
Diferent approach through Integer.parseInt
Integer.parseInt("yourInt");
To achieve your goal:
String a = "12345667788" //sample
String b = "";
int [] vecInt = new int[a.length()]; // The lack of initialization was your mistake as the above stated
for(int i=0; i< a.length(); i++)
{
b = a.substring(0,1);
a= a.substring(1);
vecInt[i] = Integer.parseInt(b);
}
Please be aware of Double, long have far higher range then Integer which might be enough in your case to avoid an array!
you forgot to initialize the array intArray
I would recommend to use a java.util.List
You forgot to initialize the array. You have written it in constructor and the variables declared in method or constructor needs to be initialize at the same time.
Note : Implementing your logic in Constructor is not recommended unless and until you dont have any other choice.
I created a class for a bingo game. I get an error saying "'class' expected". How could I return the values in the array to the main starter?
Any other comments would also be helpful.
Thank you.
import java.util.Random;
public class Card
{
Random generator = new Random();
private final int BOARDMAX = 4;
private final int NUMMAX = 59;
int i, j, m, n;
private int [][] ArrayBoard = new int[BOARDMAX][BOARDMAX];
String [][] StrArrayBoard = new String [BOARDMAX][BOARDMAX];
public void RandomNumGenerator()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
ArrayBoard[i][j] = generator.nextInt (NUMMAX+1);
}
}
}
public String ShowBoard()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
m=i;
n=j;
if (j != BOARDMAX)
StrArrayBoard[m][n] = ArrayBoard[m][n] + " ";
else
StrArrayBoard[m][n] = ArrayBoard[m][n] + " \n";
}
}
return StrArrayBoard[i][j];
}
public void ShowMark()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
if (CardCheck [i][j] == 1)
StrArrayBoard[i][j] = ArrayBoard[i][j] + "* ";
else
StrArrayBoard[i][j] = ArrayBoard[i][j] + " ";
if (j == BOARDMAX)
ArrayBoard[i][j] = ArrayBoard[i][j] + "\n";
}
}
}
public String toString()
{
return ArrayBoard[][];
}
}
With toString() you need to return a String object but actually you try to return an int[][]. The same is true for ShowBoard, you try to return an array of Stringarrays which is not a compatible type.
Here's the fix:
public String ShowBoard() {
// your code to populate StrArrayBoard
StringBuilder boardBuilder = new StringBuilder();
for (String[] row:StrArrayBoard)
for (String cell:row)
sb.append(cell);
return boardBuilder.toString();
}
public String toString() {
return ShowBoard();
}
I suggest to refactor the code and rename methods and fields:
ShowBoard() --> getBoardAsString()
ArrayBoard --> arrayBoard
StrArrayBoard --> strArrayBoard
And there's no need to declare StrArrayBoard as a field (class member) just because you only need it inside the ShowBoard method. Declare it there as a local variable.
Adding to the bugs others have pointed:
You have if (CardCheck [i][j] == 1), but the array CardCheck is not declared anywhere.
You have ArrayBoard[i][j] = ArrayBoard[i][j] + "\n"; but ArrayBoard is an int array, you cannot add a string "\n" to it's member.
The compiler will complain because of the error on your code:
public String toString()
{
return ArrayBoard[][];
}
It can't convert int[][] (which is your ArrayBoard) to String. My suggestion is that you populate all values stored in StrArrayBoard in a StringBuffer and return the StringBuffer.toString() in the toString() method.
The toString() method requires a String.
Hope this helps.
public String toString()
{
return ArrayBoard[][];
}
This method expects to return a String but you are returning a 2D Integer array, what you need is a String. the toString() method returns a string representation of the object, so in this case, what you can do is to use a StringBuilder to build the string representation of the array and then, use the .toString() of the StringBuilder to return the string representing the 2D Array.
Also, as noted by Alois Cochard, you variable naming does not follow convention. Variable names in Java use a camel case notation.
I for one don't really understand your question but I've got a couple of comments.
The class variables i and j should be local variables in each method.
Your naming convention is nonstandard, seems like a more C# convention. Start variable and method names with a lower case.
CardCheck isn't defined anywhere. I presume it is meant to indicate if a number on a square has been checked, in which case it should be a boolean and not an int.
toString doesnt return a string. You can use Arrays.toString to help you.
Similarily, ShowBoard just returns one element of an array, you probably wanted to show the entire board there.
For your toString and ShowBoard methods you probably want to use a StringBuilder to build up the string representation.
StringBuilder builder = new StringBuilder();
for (int i=0; i<BOARDMAX; i++) {
for (int j=0; j<BOARDMAX; j++) {
builder.append(StrArrayBoard[i][j]);
}
builder.append('\n');
}
return builder.toString();
Here's a version of your class that compiles (and I changed some field names and modifiers to adhere to standard conventions). Try this:
public class Card{
private final Random generator = new Random();
private static final int BOARDMAX = 4;
private static final int NUMMAX = 59;
int i, j, m, n;
private final int[][] arrayBoard = new int[BOARDMAX][BOARDMAX];
private final String[][] strArrayBoard = new String[BOARDMAX][BOARDMAX];
// do something here please
private int[][] CardCheck;
public void RandomNumGenerator(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
arrayBoard[i][j] = generator.nextInt(NUMMAX + 1);
}
}
}
public String ShowBoard(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
m = i;
n = j;
if(j != BOARDMAX){
strArrayBoard[m][n] = arrayBoard[m][n] + " ";
} else{
strArrayBoard[m][n] = arrayBoard[m][n] + " \n";
}
}
}
return strArrayBoard[i][j];
}
public void ShowMark(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
if(CardCheck[i][j] == 1){
strArrayBoard[i][j] = arrayBoard[i][j] + "* ";
} else{
strArrayBoard[i][j] = arrayBoard[i][j] + " ";
}
if(j == BOARDMAX){
// this is probably what you mean:
strArrayBoard[i][j] = arrayBoard[i][j] + "\n";
}
}
}
}
#Override
public String toString(){
// this is probably what you mean:
return Arrays.deepToString(strArrayBoard);
}
}