Problems at detecting spacebars at Strings - java

So I'm doing a program that takes a user input and when it finds chars that are similar to numbers, it replaces it by the number. (For example, it replaces O's by 0's, e's by 3's, etc) The problem is that when it finds a blank space it all messes up. You can check by compiling the code that the output is completely messed up.
/* Program to encrypt text replacing some letters by similar numbers
Done by: Gabriel Mello
*/
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String input; //Allocating space for user input
char[] output=new char[100000]; //Allocating space for final output
while(true){ // Lets it work as many times as wished
System.out.println("EscribĂ­ la frase que quieras transformar"); // Spanish for input your frase
input=sc.next(); //Takes user input
for(int i=0; i<=input.length()-1;i++){ //Iterates over every char in the input
switch(input.charAt(i)){//Checks wether the current digit is valid for replacement,
case 'O': // if it is, it replaces it, if not, it leaves it as it is.
case 'o': output[i]='0';
break;
case 'L':
case 'l':
case 'I':
case 'i': output[i]='1';
break;
case 'Z':
case 'z': output[i]='2';
break;
case 'E':
case 'e': output[i]='3';
break;
case 'A':
case 'a': output[i]='4';
break;
case 'S':
case 's': output[i]='5';
break;
case 'G':
case 'g': output[i]='6';
break;
case 'T':
case 't': output[i]='7';
break;
case 'B':
case 'b': output[i]='8';
break;
case 'P':
case 'p': output[i]='9';
break;
default: output[i]=input.charAt(i);
}
}
System.out.println(output); //Prints the output
for(int i=0;i<=output.length-1;i++){ //Resets the output array
output[i]=' ';
}
}
}
}

The Scanner input splits at spaces. So if you type in 12 34 the first input your code sees is 12. It Runs through the for(int i=0; i<=input.length()-1;i++) loop, then the while loop finds another input 34 and again runs through it. See the Java doc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Replace input=sc.next() by input=sc.nextLine() to fix it.

Related

Java: How to deal with string index out of range error?

I'm new to Java and I can't figure out how to solve this problem:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
Here's the entire code:
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
//Step 1: Ask user to enter first and last name
System.out.println("\nPlease enter your first and last name: ");
String name = input.nextLine();
String major = "";
String classification = "";
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
char ch = input.next().charAt(0);
char ch1 = input.nextLine().charAt(1);
//Step 3: Print statement
switch(ch) {
case 'i': major = "Information Technology"; break;
case 'c': major = "Computer Science"; break;
case 'm': major = "Mathematics"; break;
case 'p': major = "Physics"; break;
case 'b': major = "Biology"; break;
case 'e': major = "Engineering"; break;
case 'h': major = "History"; break;
case 'j': major = "Journalism"; break;
case 'a': major = "Art and Design"; break;
case 'l': major = "Literature"; break;
case 's': major = "Sport Medicine"; break;
default: System.out.println("\nInvalid Major Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
//Step 3: Print statement
switch(ch1) {
case '1': classification = "Freshman"; break;
case '2': classification = "Sophmore"; break;
case '3': classification = "Junior"; break;
case '4': classification = "Senior"; break;
case '5': classification = "Graduate"; break;
default: System.out.println("\nInvalid Classification Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
System.out.println("\nMajor and classification is: " + major + "" + classification);
System.out.println("\nThank You!");
}//end of main
Any help would be greatly appreciated.
Try to change your code so that it first checks for the length of the input before it refer to the index of the String. Something like the following:
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
String inputNext = input.next();
String inputNextLine;
if(inputNext.length>0 && inputNextLine.length>0){
char ch = inputNext;
char ch1 = inputNextLine;
//Step 3: Print statement
switch(ch)
{
case 'i': major = "Information Technology";
break;
case 'c': major = "Computer Science";
break;
case 'm': major = "Mathematics";
break;
case 'p': major = "Physics";
break;
case 'b': major = "Biology";
break;
case 'e': major = "Engineering";
break;
case 'h': major = "History";
break;
case 'j': major = "Journalism";
break;
case 'a': major = "Art and Design";
break;
case 'l': major = "Literature";
break;
case 's': major = "Sport Medicine";
break;
default: System.out.println("\nInvalid Major Code");
System.out.println("Please enter a character followed by an integer!");
break;
}//end of switch
//Step 3: Print statement
switch(ch1)
{
case '1': classification = "Freshman";
break;
case '2': classification = "Sophmore";
break;
case '3': classification = "Junior";
break;
case '4': classification = "Senior";
break;
case '5': classification = "Graduate";
break;
}
}
The problem is that char ch = input.next().charAt(0); will read both the characters, but not "consume" the newline character that is generated when the user hits Enter.
You then call input.nextLine(), which will consume the newline character (but now the two characters were already consumed by next(), so the resulting string is empty). Calling .charAt(1) on the empty string generates the exception because there is no position (1) in the empty string (it's length is 0).
Instead I'd suggest you use something like this:
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
String majorAndClassification = "";
while( majorAndClassification.length() != 2 )
majorAndClassification = input.nextLine();
char ch = majorAndClassification.charAt(0);
char ch1 = majorAndClassification.charAt(1);
This will make sure that the user enters two characters - if he doesn't, he'll have to try again until he does. A slightly better option would of course be to print out the prompt every time, like so:
//Step 2: Ask user to enter two characters
String majorAndClassification = "";
while( majorAndClassification.length() != 2 ){
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
majorAndClassification = input.nextLine();
}
If you enter the second entered character, it reads out of range because of charAt(1). Just change it to charAt(0), because you alwayws read only the first character of the input:
char ch = input.next().charAt(0);
char ch1 = input.next().charAt(0);
It works for both inputs:
i
3
And also i 3
change your code from char ch1 = input.nextLine().charAt(1);
to this char ch1 = input.next().charAt(0);
you can check this for more details about differences between next() and nextLine()
Calling
final char ch1 = input.nextLine().charAt(1);
expects a whole line to be read, and there getting the second letter.
But
char ch = input.next().charAt(0);
already consumed the first char.
So you should read the whole input in one go, then (do more checking and then) get your chars.
//Step 2: Ask user to enter two characters
System.out.println("\nPlease enter two characters (1st character represents the major and 2nd character represents the classification): ");
final String reply = input.nextLine();
final char ch = reply.charAt(0);
final char ch1 = reply.charAt(1);
//Step 3: Print statement

Convert phonenumber(string) to integer number (Revised) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Question
Write a method that returns a number, given an uppercase letter, as follows.
int getNumber (char uppercaseLetter)
Write a test program that prompts the user to enter a phone number as a string. The input number may contain letters. The program translates a letter (uppercase or lowercase) to a digit and leaves all other characters intact.
Sample run from textbook
Enter a string: 1-800-Flowers
1-800-3569377
Enter a string: 1800flowers
18003569377
Here is what I have so far
import java.util.Scanner;
public class Assignment {
public static int correspondingNumber(char uppercaseLetter){
int correspondingNumber=0;
switch (uppercaseLetter)
{
case 'A':
case 'B':
case 'C': correspondingNumber=2; break;
case 'D':
case 'E':
case 'F': correspondingNumber=3; break;
case 'G':
case 'H':
case 'I': correspondingNumber=4; break;
case 'J':
case 'K':
case 'L': correspondingNumber=5; break;
case 'M':
case 'N':
case 'O': correspondingNumber=6; break;
case 'P':
case 'Q':
case 'R':
case 'S': correspondingNumber=7; break;
case 'T':
case 'U':
case 'V': correspondingNumber=8; break;
case 'W':
case 'X':
case 'Y':
case 'Z': correspondingNumber=9; break;
}
return correspondingNumber;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String num;
char num1 = 0;
System.out.print("Enter a string: ");
num = input.next();
num.toUpperCase();
int i=0;
while(i!=num.length()){
num1=num.charAt(i);
}
System.out.print(correspondingNumber(num1));
}
}
steps need tobe done
scan input let's say as String
Convert string to character array (srcArray)
change method return of correspondingNumber to Char
default return to input and apply switch case
call method correspondingNumber, store return char in stringbuilder or Array of Char array
repeat step-5 until character array(srcArray) is completely processed
print the output
import java.util.Scanner;
public class Assignment {
// changed return type
public static char correspondingNumber(char uppercaseLetter) {
char correspondingNumber = uppercaseLetter;// default the return value
// to input
switch (uppercaseLetter) {
case 'A':
case 'B':
case 'C':
correspondingNumber = '2';
break;
case 'D':
case 'E':
case 'F':
correspondingNumber = '3';
break;
case 'G':
case 'H':
case 'I':
correspondingNumber = '4';
break;
case 'J':
case 'K':
case 'L':
correspondingNumber = '5';
break;
case 'M':
case 'N':
case 'O':
correspondingNumber = '6';
break;
case 'P':
case 'Q':
case 'R':
case 'S':
correspondingNumber = '7';
break;
case 'T':
case 'U':
case 'V':
correspondingNumber = '8';
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
correspondingNumber = '9';
break;
}
return correspondingNumber;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String num;
char num1 = 0;
System.out.print("Enter a string: ");
num = input.next();
num.toUpperCase();
int i = 0;
while (i != num.length()) {
num1 = num.charAt(i);
System.out.print(correspondingNumber(num1)); // moved print
// statement to
// appropriate place
i++; // iterate loop
}
input.close();
}
}

Trying to save the first 3 words of each line from a text file, java

So I'm trying to do a private project using a text file and the robot class to read the first 3 words in each line and using the robot Object to input those words into another windows application.
The text file will look like that and it can have many more lines and every word is separated by a tab.
abc def hij klm opq rstu
cba fed jih mlk qpo utsr
Now, I want to store the first 3 words from each line and use them with the Robot Object, which works perfectly fine the way I need it to work.
I can read the whole line and separate the words, but not just the first 3 words.
I just learned how to write and how to read from a file using the Scanner Object, so I would like to keep using this method.
Help would be really appreciated.
Here's my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class IO_Example_03 {
public static void main(String[] args) throws FileNotFoundException, AWTException {
run(); // Runs the main program.
Robot r2 = new Robot();
r2.keyPress(KeyEvent.VK_ENTER);
}
public static void run() throws AWTException, FileNotFoundException {
Robot r1 = new Robot();
// Put the file path, separated by \\
File f = new File("filename.txt");
Scanner in = new Scanner(f);
ArrayList<String> newArr = new ArrayList<String>();
while (in.hasNext()) {
// Inputs all the words from the file that are separated by a Tab.
String input = in.next();
// Adds all the words to the ArrayList, one by one
newArr.add(input);
}
try {
// How much time in milliseconds to pause, to give the user time to
// open the desired application. 1000 milliseconds = 1 second.
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// An outer loop that go the beginning until the end of the ArrayList
for (int i = 0; i < newArr.size(); i++) {
// An inner loop that takes each word separate from the ArrayList.
for (int j = 0; j < newArr.get(i).length(); j++) {
// Saves to the singleChar variable each character from
// individual word. Also, it makes all the words as a lower case.
char singleChar = newArr.get(i).toLowerCase().charAt(j);
key(singleChar); // Invoking the key method.
try {
// How much time in milliseconds to pause between each character.
// 1000 milliseconds = 1 second.
Thread.sleep(99);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
r1.keyPress(KeyEvent.VK_ENTER); // A delimiter like Enter, Tab, or Period.
}
}
// A switch method that takes each character, and convert it into a KeyPress robot object.
public static void key(char character) throws AWTException {
Robot r = new Robot();
switch (character) {
case 'a': r.keyPress(KeyEvent.VK_A); break;
case 'b': r.keyPress(KeyEvent.VK_B); break;
case 'c': r.keyPress(KeyEvent.VK_C); break;
case 'd': r.keyPress(KeyEvent.VK_D); break;
case 'e': r.keyPress(KeyEvent.VK_E); break;
case 'f': r.keyPress(KeyEvent.VK_F); break;
case 'g': r.keyPress(KeyEvent.VK_G); break;
case 'h': r.keyPress(KeyEvent.VK_H); break;
case 'i': r.keyPress(KeyEvent.VK_I); break;
case 'j': r.keyPress(KeyEvent.VK_J); break;
case 'k': r.keyPress(KeyEvent.VK_K); break;
case 'l': r.keyPress(KeyEvent.VK_L); break;
case 'm': r.keyPress(KeyEvent.VK_M); break;
case 'n': r.keyPress(KeyEvent.VK_N); break;
case 'o': r.keyPress(KeyEvent.VK_O); break;
case 'p': r.keyPress(KeyEvent.VK_P); break;
case 'q': r.keyPress(KeyEvent.VK_Q); break;
case 'r': r.keyPress(KeyEvent.VK_R); break;
case 's': r.keyPress(KeyEvent.VK_S); break;
case 't': r.keyPress(KeyEvent.VK_T); break;
case 'u': r.keyPress(KeyEvent.VK_U); break;
case 'v': r.keyPress(KeyEvent.VK_V); break;
case 'w': r.keyPress(KeyEvent.VK_W); break;
case 'x': r.keyPress(KeyEvent.VK_X); break;
case 'y': r.keyPress(KeyEvent.VK_Y); break;
case 'z': r.keyPress(KeyEvent.VK_Z); break;
case '1': r.keyPress(KeyEvent.VK_1); break;
case '2': r.keyPress(KeyEvent.VK_2); break;
case '3': r.keyPress(KeyEvent.VK_3); break;
case '4': r.keyPress(KeyEvent.VK_4); break;
case '5': r.keyPress(KeyEvent.VK_5); break;
case '6': r.keyPress(KeyEvent.VK_6); break;
case '7': r.keyPress(KeyEvent.VK_7); break;
case '8': r.keyPress(KeyEvent.VK_8); break;
case '9': r.keyPress(KeyEvent.VK_9); break;
case '0': r.keyPress(KeyEvent.VK_0); break;
case '-': `enter code here`
r.keyPress(KeyEvent.VK_MINUS);
}
}
}
String#split() is what you are looking for.
When reading the file line by line, just split the returned String by \t (Tab character).
Your desired first three words will be the indices 0 to 2.
while (in.hasNext()) {
String[] words = in.nextLine().split("\t");
for (int i = 0; i < 3; i++) {
newArr.add(words[i]);
}
}
You could try reading each line individually with String line = in.nextLine(), then you could make an array of each word in each line by doing String[] words = line.split("\t"). Then you could access the first three words of that line by words[0], words[1], and words[2].
Here's some sample code:
while (in.hasNext()) {
String input = in.nextLine();
String[] words = input.split("\t");
newArr.add(words[0]);
newArr.add(words[1]);
newArr.add(words[2]);
}

Determine the user input is either a vowel or not using switch statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public class vowel {
private static int ch;
public static void main(String[]args){
char vowel;
Scanner sc = new Scanner(System.in);
System.out.println("Enter alphabet:" );
vowel=sc.next().charAt(0);
switch (ch){
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
System.out.println("This is a Vowel:"+ vowel);
break;
default:
System.out.println("This is not a Vowel:"+ vowel);
break;
}
}
}
the problem is that no matter what letter i enter, it will always have an outcome of saying 'This is not a Vowel' although it is.
Since vowel is the letter you are looking at, you need to add that to your switch statement. The first code you provided didn't know what variable you were using for comparison.
switch(vowel){ //You need something here.
case 'a':
case 'A':
// continue with other vowels
System.out.println("This is a Vowel:"+ vowel);
break;
default:
System.out.println("This is not a Vowel:"+ vowel);
break;
}
Don't switch on ch, you aren't even using that in the code you provided. Unless you are using that somewhere else in your code, you can remove it completely.
EDIT
If you want to look at a whole string and check each char for whether or not it is a vowel try something like this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: " ); //Better prompt IMO
String str = sc.next(); //Get the whole string
char[] myChar = str.toCharArray(); //Turn the string into an array of char
for (char c : myChar) { //For every char in the array
switch (c) { //Check if it is a vowel or not
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
System.out.println(c + " - Vowel"); //Easier for me to read
break;
default:
System.out.println(c);
break;
}
}
}

Using throws java.io.IOException and getting System.in.read(); to access a case via an integer

I only need help with the input part. If the user inputs a number I need the program to read and output a case that equals the number that was input.
//This program will display the months of the year
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
int month;
System.out.println("Please enter a Month Number: ");
month = (int) System.in.read(); //Get an integer
switch (month) {
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
case 3: System.out.println("March");
break;
case 4: System.out.println("April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println("June");
break;
case 7: System.out.println("July");
break;
case 8: System.out.println("August");
break;
case 9: System.out.println("September");
break;
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}
Try using the Console class instead: http://docs.oracle.com/javase/6/docs/api/java/io/Console.html to obtain user input, then convert the String to a number with Integer.parseInt(String)
Also, be aware that the next version of Java (8) will support Strings in case blocks.
class vehicle
{
int passengers;
int fuelcap;
int mpg;
}
import java.io.*;
class Vehicle_Demo
{
public static void main (String args[]) throws java.io.IOException
{
vehicle obj1 = new vehicle();
obj1.passengers=12;
obj1.fuelcap=9;
obj1.mpg=78;
System.out.println(obj1.passengers, obj1.fuelcap, obj1.mpg);
}
}
You can use Scanner to read your System.in
Scanner input = new Scanner(System.in);
month = input.nextInt();
Output:
Please enter a Month Number:
1
January
See related
Edit:
as noahz pointed out there is a Console class that covers the same functionality. For an idea of the difference between the two, read this.
Try to use TextIO Input Functions
This is better than scanner input
You need to compile TextIO.java fist as a prerequisite so that TextIO.class must be found in the same folder.
use this input function instead:
month = TextIO.getChar();
Please let me know if you have problems on this method.
Thanks!
Correct me if I'm wrong, but I'm pretty sure it will still work with "system.in.read". You're switch cases do not have single quotes around the input you want to be processed. If you want case one to be run when you type '1' your case should be case '1', not case 1.
There problem here was Java have cast a character to an integer, therefore you get an ASCII value.
For instance, when you type 5 you've got 53 in ASCII. Check it taking the variable value in System.out.println();
I've tried to solve that changing month to a char type and then passing a char value to the switch control. But the problem is, getting System.in.read(); method you just can get a single character. At last you just can select between 1 to 9.
I suspect the solution is using a buffer reader. Until then, I leave you here my code:
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
char month;
System.out.println("Please enter a Month Number: ");
month = (char) System.in.read(); //Get an integer
//System.out.println("Actual value of :" + month);
switch (month) {
case '1': System.out.println("January");
break;
case '2': System.out.println("February");
break;
case '3': System.out.println("March");
break;
case '4': System.out.println("April");
break;
case '5': System.out.println("May");
break;
case '6': System.out.println("June");
break;
case '7': System.out.println("July");
break;
case '8': System.out.println("August");
break;
case '9': System.out.println("September");
break;
/*case '10': System.out.println("October");
break;
case '11': System.out.println("November");
break;
case '12': System.out.println("December");
break;*/
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}

Categories

Resources