Scanner user_input = new Scanner( System.in );
String cipher_input = user_input.nextLine();
String[] arr_cipher_input = cipher_input.split("");
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
arr_ctext[i] = (int) arr_cipher_input[i].charAt(i);
}
The above code takes an input and splits it into an array (e.g. "hello" becomes ["h","e","l","l","o"]) and then I attempt to convert the characters to their ascii values which is where it returns the error in the title. It correctly converts the first character every time and then stops on the second and I can't seem to figure out why. The array lengths seem to be the same so I'm not sure what I'm doing wrong. I'd appreciate any help. Thanks in advance!
You are creating a number of one character String(s). But you are trying to access subsequent characters. There aren't any. Change charAt(i) to charAt(0) to fix. Like,
arr_ctext[i] = (int) arr_cipher_input[i].charAt(0);
or (more efficiently) skip the split and access the characters in the input directly. Like,
String cipher_input = user_input.nextLine();
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
arr_ctext[i] = (int) cipher_input.charAt(i);
}
Related
The code below runs perfectly fine if the text file consists of lines of numbers but once it gets to for example a line that says "I am 40" it skips it instead of putting 40 into the array.
Scanner inFile = null;
File file = null;
String filePath = (JOptionPane.showInputDialog("Please enter a file path"));
int size = 0;
int[] result = new int[10];
try {
file = new File(filePath);
inFile = new Scanner(file);
int skippedCounter = 0;
for(int i = 0; inFile.hasNext(); i++){
if(inFile.hasNextInt())
result[i] = inFile.nextInt();
else{
String strOut = "";
String data = inFile.next();
for(int j = 0; j <= data.length() - 1; j++){
if(!Character.isLetter(data.charAt(j))){
strOut += data.charAt(j);
}
else
skippedCounter++;
}
result[i] = Integer.parseInt(strOut);
}
}
}
next() will give you the next token not the next Line. so variable i may go past ten. you would realize this if you didnt have an empty catch : that your array is going out of bounds
solution:
don't use a result array, use a result list, and append to its end whenever you have another result
note:
another hidden exception that could be occurring is when your parseInt fails due to non-numeric data. So don't wrap everything in a giant try/catch, it just makes it harder to debug!
I suggest you to use nextInt function just one time to keep the requested value, then use that variable whenever you need it. I think nextInt function moves to the next int each time you appeal it.
The following
result[i] = Integer.parseInt(strOut)
will result in a NumberFormatException when trying to process any letter. As strOut results in an empty String ""
You'll have to check for an empty String before attempting to parse
if (!strOut.isEmpty()) {
result[i] = Integer.parseInt(strOut);
}
I need to write a program that let's the user write 3 words in the console, then the program reprints those 3 words (one in each line) but also fills out the remaining spaces in each line with dots (".") so the total number of characters in each lines becomes a total of 30 characters.
Example:
Input:
Hello
Me
Overflow
Output:
.........................Hello
............................Me
......................Overflow
This is the code that I currently have which generates an error. I have been given the code (at the bottom) as part of my assignment and need to write the repeatChar method to make it work.
The first thing I did was to add the following commands in the code, in order to save the 3 words into the array threeWord.
threeWord[1] = wordOne;
threeWord[2] = wordTwo;
threeWord[3] = wordThree;
Next, I had to write the method repeatChar, and I decided to use a for-loop to make it repeat dots for each individual line, but I'm having a hard time making it fit with the rest of the code. Any guidance would be much appreciated, thanks.
import java.util.*;
public class FillDots {
private static int LineLength = 30;
public static void main(String[] arg) {
String[] threeWord = new String [3]; // Defines 3 locations to place strings in the array "threeWord"
Scanner console = new Scanner(System.in);
System.out.println("Type in three words:");
String wordOne = console.next();
threeWord[1] = wordOne; // Saves first word to array "threeWord"
String wordTwo = console.next();
threeWord[2] = wordTwo; // Saves second word to array "threeWord"
String wordThree = console.next();
threeWord[3] = wordThree; // Saves third word to array "threeWord"
for(int i = 0; i < threeWord.length; i++) {
System.out.println(repeatChar('.', LineLength - threeWord[i].length()) + threeWord[i]);
}
}
public static String repeatChar(String LineLength) {
for(int j = 0; j < LineLength; j++) {
System.out.print(".");
}
}
}
Besides the index starts from 0, you need return the dots in the repeatChar method:
public static String repeatChar(char repeatChar, int repeatTimes) {
String result = "";
for(int j = 0; j < repeatTimes; j++) {
result += repeatChar;
}
return result;
}
You can use existing library for doing padding
for(String temp:threeWord)
system.out.println(org.apache.commons.lang.StringUtils.leftPad(temp, 10, ".") );
this might simplify your code
I'm slowly trying to write a program that will convert a hexadecimal number to a decimal. I'm not interested in reading finished, well known codes because I want do it myself. I have an idea but there is something interfering me.
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String any = input.nextLine();
char[] cArray = any.toCharArray();
for(int i=0; i<cArray.length; i++){
System.out.print(cArray[i]+" ");
}
}
}
Input: ab12
Output: a b 1 2
I want replace a with 10, b with 11, c with 12, etc.
It works if I add an if-statement inside the for-loop.
for(int i=0; i<cArray.length; i++){
if(cArray[i] == 'a'){
cArray[i] = '10'; // doesn't work, read below
}
System.out.print(cArray[i]+" ");
}
The problem is I want replace a with 10 and 10 isn't a character anymore since it's made up of two letters. That's why I'd like to know how to make this code work with strings instead of characters?
Hint
'a' - 87 = 10
So you can use:
(int) cArray[i] - 87
Because :
(int)'a' = 97
Hope you get the idea.
Instead of replacing the values in cArray, I'd create a StringBuilder, and append all the values to that (since presumably you only want to print out the result):-
StringBuilder str = new StringBuilder();
for(int i=0; i<cArray.length; i++){
if(cArray[i] == 'a'){
str.append(10);
} else if (cArray[i] == 'b'){
[etc]
} else {
str.append(cArray[i]);
}
}
System.out.print(str.toString());
I am guessing that you would want to access the converted decimal digits after extracting them. Use List of String to store your output
Scanner in = new Scanner(System.in);
String any = in.nextLine();
char[] cArray = any.toCharArray();
List<String> output = new ArrayList<String>();
for(int i=0; i<cArray.length; i++){
if(cArray[i] >= 'a'){ // Strore a,b,c,d,e
output.add(String.valueOf(10+(cArray[i]-'a')));
} else { // Store numbers
output.add(String.valueOf(cArray[i]));
}
}
for(String s : output){
System.out.println(s);
}
Let's take a look at this:
if (cArray[i] == 'a') {
cArray[i] = '10';
}
This is not valid Java for a couple of reasons:
'10' is not a valid literal. It isn't a character literal because there are two characters ... and a character literal can only represent a single character. It isn't a String literal either, because a String literal is enclosed with double-quote characters; e.g. "10".
Assuming we change '10' to "10" ... it is still wrong. Now the problem is that cArray[i] = "10"; is assigning a String object into an array of characters.
The next problem is that you can't "insert" into an array. Arrays have fixed sizes. The size of an array cannot change (unless you make a new array). All you can do is update the character at a given position.
But that doesn't work here either. You could try to move the characters to the right to make space for the extra characters. However, then you wouldn't have enough space in the array to hold all of the characters.
In short, you need to represent the modified / rewritten characters as a new data structure. The StringBuilder class is the most suitable. See #SteveSmith's answer for a solution using StringBuilder.
To make your code work with a string instead of character change the char array to string array:
Scanner input = new Scanner(System.in);
String any = input.nextLine();
//char[] cArray = any.toCharArray(); // first change this line
String [] cArray = any.split(""); // split input into single characters as string
for(int i=0; i<cArray.length; i++){
System.out.print(cArray[i]+" ");
}
for(int i=0; i<cArray.length; i++){
if(cArray[i].equals("a")){ // use String.equals("anotherString") method to check equality
cArray[i] = "10";
}
System.out.print(cArray[i]+" ");
}
I am having problems with replacing the characters in the char array. I have tried the .replace method, but it does not seem to work. So do you know how to replace the letters in the char array, with the char variable GuessedLetter. This is code whole code I've developed so far:
import java.util.Scanner;
public class Hangman{
public static void main(String []args){
Scanner Input = new Scanner(System.in);
String[] CollectionOfWords = {"apple","banana","pear","plum","watermelon"};
int RadmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length);
String RadmWord = CollectionOfWords[RadmNumber];
System.out.println(RadmWord);
char[] GenRadmLetter = RadmWord.toCharArray();
char[] GenRadmLetter2 = RadmWord.toCharArray();
for (int x = 0; x<GenRadmLetter.length; x++){
GenRadmLetter[x]='?';
}
System.out.println(String.valueOf(GenRadmLetter));
Scanner input = new Scanner(System.in);
System.out.println("Hello. Guess a letter.");
char GuessedLetter = Input.next().charAt(0);
int RW = RadmWord.indexOf(GuessedLetter);
String GenRadmLetterStr = String.valueOf(GenRadmLetter);
}
}
Thank you,
You are trying to modify a String.
This class is immutable, so when you try something such as:
GenRadmLetter[x]='?';
You are not modifying the data inside the RadmWord.
What you could do, is something such as:
char[] GenRadmLetter2 = new char[RadmWord.length];
for (int x = 0; x < RadmWord.length; x++){
GenRadmLetter[x]='?';
}
String result = new String(GenRadmLetter2);
Although, you may wish to keep the displayed String as a character array to allow easy changes to the display.
Firstly, variable names should begin with a lowercase letter as such. A capital letter implies a class type. This is a very standard convention when it comes to Java, and as such it helps readability when sharing code with others.
String radmWord = collectionOfWords[radmNumber];
Secondly, the method String.indexOf(Char) only returns the first index of that character within the string. Since you would want to be replacing all occurrences of that character you would want to actually loop through the word checking each character to see if it is the character that was guessed. From there you could then replace that index within your guessing word. Take a look at this code I put together as an example, it should help you figure out what you need to do:
String randomWord = "apple";
String guessWord = "?????";
char guess = 'p';
for (int i = 0; i < randomWord.length(); i++) {
if (randomWord.charAt(i) == guess) {
char[] tempGuess = guessWord.toCharArray();
tempGuess[i] = guess;
guessWord = Arrays.toString(tempGuess);
}
}
i am writing a code that reads input from a file and writes into another after some processing ofcourse.
now, my input file is,
4
0 1
0 2
0
0 3
3
0
0
0
E
and what i need to do is copy elements on left to an array in first column and elements on right to second column.
i used scanner but it does not recognize end of line.
help me!!!!
this is what i tried.
i tried copying lines and then modifying it.
for (i = 0; i < size; i++) {
if (!f1.hasNext(endPage)) {
String temp1 = f1.next();
String temp2 = f1.next();
int a[] = new int[4];
a[0] = (int) temp1.charAt(temp1.length() - 1);
a[1] = (int) temp2.charAt(temp1.length() - 1);
a[2] = (int) temp1.charAt(temp1.length() - 2);
a[3] = (int) temp1.charAt(temp1.length() - 2);
scales[i].weightOnLeft = a[0];
scales[i].weightOnRight = a[1];
scales[i].left = scales[a[2]];
scales[i].right = scales[a[3]];
}
}
Try this way:
Scanner input = new Scanner(new File("..."));
while(input.hasNextLine())
{
String data = input.nextLine();
}
Try to use the Scanner to read line by line and then split(on space, in your case) your line to get the tokens.
Scanner f1 = new Scanner(new File("yourFileName.extn"));
while(input.hasNextLine()) {
String line = f1.nextLine();
String[] tokens = line.split(" "); // Splitting on space
// Do what you want with your tokens
// Since not all lines have equal no. of tokens, you need to handle that accordingly
}
Try like this below:-
In your first column it will store on array[0] and second column value will store on array[1]. Also for second column you need to check the condtion as written below. Please follow:-
File file=new File("/Users/home/Desktop/a.txt");
String[] aa=new String[2];
try {
Scanner sc=new Scanner(file);
while (sc.hasNextLine())
{
String ss=sc.nextLine();
aa=ss.split("\\s");
//it will store left column value in this index
System.out.println("aa[0]"+aa[0]);
if(aa.length>1)
{
//it will store right column value in this index
System.out.println("aa[1]"+aa[1]);
}
}
}