I'm getting two small unexpected type errors which I'm having trouble trying to solve.
The errors occur at:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Any advice?
public class SwapLetters
{
public static void main(String[] args)
{
System.out.println("Enter a string: ");
String str = new String(args[0]);
String swapped = str;
char[] charArray = str.toCharArray();
System.out.println("Enter a position to swap: ");
int Swap1 = Integer.parseInt(args[1]);
System.out.println("Enter a second position to swap: ");
int Swap2 = Integer.parseInt(args[2]);
char temp1 = str.charAt(Swap1);
char temp2 = str.charAt(Swap2);
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
System.out.println("Original String = " + str);
System.out.println("Swapped String = " + swapped);
}
}
You can assign values to variables, not other values. Statements like 5 = 2 or 'a' = 'z' don't work in Java, and that's why you're getting an error. swapped.charAt(temp1) returns some char value you're trying to overwrite, it's not a reference to a particular position inside the String or a variable you can alter (also, mind that Java Strings are immutable so you can't really change them in any way after creation).
Refer to http://docs.oracle.com/javase/7/docs/api/java/lang/String.html for information on using String, it should have a solution for what you're trying to do.
Your code may even throw IndexOutOfBoundsException - if the index argument is negative or not
less than the length of this string. Check the length of each string.
The left side of your assignment cannot receive that value.
Description of String#charAt(int):
Returns the char value at the specified index
It returns the value of the character; assigning values to that returned value in the following lines is the problem:
swapped.charAt(temp1) = str.charAt(temp2);
swapped.charAt(temp2) = temp1;
Also, String#charAt(int) expects an index of a character within the String, not the character itself (i.e. chatAt(temp1) is incorrect), so your method will not work as expected even if you fix the former problem.
Try the following:
String swapped;
if(swap1 > swap2) {
swap1+=swap2;
swap2=swap1-swap2;
swap1-=swap2;
}
if(swap1!=swap2)
swapped = str.substring(0,swap1) + str.charAt(swap2) + str.substring(swap1, swap2) + str.charAt(swap1) + str.substring(swap2);
Related
I need to get the values after "Swap:".
I've already developed a method to get the output from a shell command so I have a string that contains everything you see in the picture but now from the string I want to get ONLY the value after the Swap: How can i do this? These value are variable and can be even all three 0.
Let's say you have the text stored in a String called textContent. Assuming the Swap-line is the last part of your String, then you could do something like this:
int index = textContent.indexOf("Swap:");
index += "Swap:".length();
textContent.subString(index);
Try this:
String[] stringParts = text.substring(text.indexOf("Swap:") + 5).trim().split("( )+");
int[] parts = new int[stringParts.length];
for (int i = 0; i < stringParts.length; i++)
parts[i] = Integer.parseInt(stringParts[i]);
It will fill an integer array will the values after the "Swap" part.
Since you have already stored the output of the shell command, you simply need to do some string manipulation to search and extract the relevant information. The following particular string manipulation methods might be of interest to you: trim(), indexOf(), and substring().
Below is a simple example code on how to extract the value under the total's column using the above String methods:
public class ShellOutput {
public ShellOutput() {
final String extract = "Swap:"; // the keyword to search
String shellOutput = "Swap: 75692 29657 0"; // your shell output
int position = shellOutput.indexOf(extract); // get the position of the Swap: text
if (position != -1) {
String swapLine = shellOutput.substring(position + extract.length()); // remove everything except the swap line
String numbers = swapLine.trim(); // assuming they are spaces, otherwise do some operations to remove tabs if used
int firstSpace = numbers.indexOf(' '); // get the first space or change to a tab character if it is used
String totalNumber = numbers.substring(0, firstSpace); // remove up to the first found after the number
System.out.println("Total = " + totalNumber);
} else {
System.out.println("No '" + extract + "' segment found.");
}
}
public static void main(String[] args) {
new ShellOutput();
}
}
Output: Total = 75692
I know how to use substring() but why isn't this working, the user inputs an equation like
"5t + 1" with a space before and after the "+". I want tVariable to hold the integer before it, in this case 5 and constant should hold the constant integer in this case 1, but I get an out of range error.
import java.util.*;
import javax.swing.JOptionPane;
public class project3030 {
public static void main(String[] args) {
String L1x, tVariable, constant;
L1x = JOptionPane.showInputDialog("This is the format (x=5t + 1)");
int endIndex = L1x.indexOf("t");
tVariable = L1x.substring(0, endIndex);
int beginIndex = L1x.lastIndexOf(" ");
int endIndex2 = L1x.indexOf("");
constant = L1x.substring(beginIndex, endIndex2);
System.out.println(tVariable + constant);
}
}
You need to change it to something more like
constant = L1x.substring(L1x.lastIndexOf(" ")).trim();
Then when you add the numbers, you have to Parse them before you add them.
int constantInt = Integer.parseInt(constant);
Or you could use this solution:
String[] input = L1x.split(" ");
// remove the 't'
String tNum = input[0].substring(0, input[0].length() - 1);
int t = Integer.parseInt(tNum);
int constant = Integer.parseInt(input[2]);
String operator = input[1];
if (operator == "-")
constant *= -1;
The reason you are getting this error is because your substring() range is off.
You are passing into substring() an invalid range because the first index is beginIndex which you set equal to lastIndexOf(" ") while endIndex2 you set equal to indexOf("") which will occur at the beginning of the string.
Thus, you have your ranges mixed up. When you make this statement:
constant = L1x.substring(beginIndex, endIndex2);
You're giving it an invaid range
and will cause the specified error.
You could also do it different way. Let's say you create a JFrame and there you could put a textfield for every value, so for every "t" or constants, and then it would be much more simple to get those values. For characters like t or = you could use JLabels, so it would be a mixture of JTextFields and JLabels and I think it wouldn't be that ugly. I used this solution few times.
So I'm still shaky on how basic java works, and here is a method I wrote but don't fully understand how it works anyone care to explain?
It's supposed to take a value of s in and return it in its reverse order.
Edit: Mainly the for loop is what is confusing me.
So say I input "12345" I would want my output to be "54321"
Public string reverse(String s){
String r = "";
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r;
}
return r;
}
We do a for loop to the last index of String a , add tha carater of index i to the String s , add here is a concatenation :
Example
String z="hello";
String x="world";
==> x+z="world hello" #different to z+x ="hello world"
for your case :
String s="";
String a="1234";
s=a.charAt(0)+s ==> s= "1" + "" = "1" ( + : concatenation )
s=a.charAt(1)+s ==> s='2'+"1" = "21" ( + : concatenation )
s=a.charAt(2)+s ==> s='3'+"21" = "321" ( + : concatenation )
s=a.charAt(3)+s ==> s='3'+"321" = "4321" ( + : concatenation )
etc..
public String reverse(String s){
String r = ""; //this is the ouput , initialized to " "
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r; //add to String r , the caracter of index i
}
return r;
}
What this code does is the following
Create a new variable r="";
then looping for the string in input lenght it adds at the beginning of r the current character of the loop.
i=0) r="1"
i=1) r="21"
i=2) r="321"
i=3) r="4321"
i=4) r="54321"
When you enter the loop you are having empty string in r.
Now r=""
In 1st iteration, you are taking first character (i=0) and appending r to it.
r = "1" + "";
Now r=1
In 2nd iteration, you are taking second character (i=1) and appending r to it
r = "2" + "1";
Now r=21
You can trace execution on a paper like this, then you will easily understand what is happening.
What the method is doing is taking the each character from the string s and putting it at the front of the new string r. Renaming the variables may help illustrate this.
public String reverse(String s){
String alreadyReversed = "";
for(int i=0; i<s.length(); i++){
//perform the following until count i is as long as string s
char thisCharacterInTheString = s.charAt(i); // for i==0 returns first
// character in passed String
alreadyReversed = thisCharacterInTheString + alreadyReversed;
}
return alreadyReversed;
}
So in the first iteration of the for loop alreadyReversed equals 1 + itself (an empty string).
In the second iteration alreadyReversed equals 2 + itself (1).
Then 3 + itself (21).
Then 4 + 321.
Then 5 + 4321.
GO back to your problem statement (take an input string and produce an output string in reverse order). Then consider how you would do this (not how to write Java code to do this).
You would probably come up with two alternatives:
Starting at the back of the input string, get one character at a time and form a new string (thus reversing its order).
Starting at the front of the string, get a character. Then for each next character, put it in front of all the characters you have created so far.
Your pseudo code results might be like the following
Option 1
let l = the length of the input string
set the output string to ""
while l > 0
add the "lth" character of the input string to the output string
subtract 1 from l
Option 2 left as an exercise for the questioner.
Then you would consider how to write Java to handle your algorithm. You will find that there are several ways to get the "lth" character of a string. First, in Java a string of length l has characters in position 0 through l-1. You can use string.charAt(loc) or string.substring(loc,loc+1) to get the character at position loc
I am trying to place spaces in between a number that has been entered in a textfield. I am using the following code:
for(int i = 0; i <= 2; i++)
{
char cijfer = tf1.getText().charAt(i);
char getal1 = tf1.getText().charAt(0);
char getal2 = tf1.getText().charAt(1);
char getal3 = tf1.getText().charAt(2);
}
String uitvoerGetal = getal1 + " " + getal2 + " " + getal3;
I suppose I don't understand the charAt() function yet, does anyone have a link explaining it in a way so I might be able to make this work too? Thanks in advance!
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces the following result:
a
In more Detail From java docs
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
In straight words You can't. You can't add space in int datatype because int is meant to store the integer value only. Change int to String to store the space in between.
Okay, let's see what's wrong with your code...
Your for-loop is 1-based instead of the standard 0-based. That's not good at all.
You're attempting to assign a char to a String (3 times), the first call to charAt is correct, but for some reason you then switch to using a String?
Finally you're attempting to assign a String to an int, which is just completely nonsensical.
You have a number of problems, but well done on an honest attempt.
First up, the indexes in a string are zero-based, so charAt(0) gives you the first character, charAt(1) gives you the second character, and so on.
Secondly, repeating all your calls to charAt three times is probably unnecessary.
Thirdly, you must be careful with your types. The return value from charAt is a char, not a String, so you can't assign it to a String variable. Likewise, on the last line, don't assign a String to an int variable.
Lastly, I don't think you've thought about what happens if the text field doesn't contain enough characters.
Bearing these points in mind, please try again, and ask for further help if you need it.
Try following code
String text = tf1.getText(); // get string from jtextfield
StringBuilder finalString = new StringBuilder();
for(int index = 0; index <text.length(); index++){
finalString.append(text.charAt(index) + " "); // add spaces
}
tf1.setText(finalString.toString().trim()) // set string to jtextfield
The code below is giving problems, I just need to turn a letter from a string into a character, and when I run my testing, I keep getting an error when the code gets to char c = t.charAt(0); The exact error message is:
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
I cannot get it to just turn the string letter into a char. Any tips would be greatly appreciated.
String[] zombies;
int num = 0;
Vector<Zombie> practice = new Vector<Zombie>();
String zombieString = "SZI1";
zombies = zombieString.split("");
for (String t : zombies) {
if (isNumeric(t)) {
int multiplier = Integer.parseInt(t);
String extraZombie = zombies[num - 1];
char x = extraZombie.charAt(0);
for (int i = 0; i <= multiplier; i++) {
Zombie zombie = Zombie.makeZombie(x);
practice.add(zombie);
}
} else {
char c = t.charAt(0);
//Zombie zombie = Zombie.makeZombie(c);
//practice.add(zombie);
num++;
}
}
Your split("") returns an empty string, and if you call charAt(0) on an empty string it will give this error.
To solve this you could replace the split("") operation with toCharArray(), this will directly generate an array of chars:
char[] zombies = zombieString.toCharArray();
Since it says "string index out of range 0", then your string has no characters in it. Might have something to do with the fact that you're telling String.split() to split on an empty string, when it needs a string delimiter on which to split.
Quoted:
https://stackoverflow.com/a/5235439/2214674
"SZI1".toCharArray()
But if you need strings
"SZI1".split("")
Edit: which will return an empty first value (extra empty String => [, S, Z, I,1].).