How to add enter to this string array? - java

can you help me on this?
I have this code which is a part of my program :
Scanner a5 = new Scanner(System.in);
while(a5.hasNextLine()) //store every line in mail message until user type "." on a seperate line
{
String text = a5.nextLine();
if (text.charAt(0) != '.')
{txt.add(text);}
else if(text.charAt(0) == '.' )
{break;}
}
I want user to type a message and until he doesn't type "." in a separate line he can add more lines. but my problem is when I press enter I get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 0
at java.lang.String.charAt(Unknown Source)
at MyPMC.main(MyPMC.java:51)
how can I fix it so it also add empty line to my string?
example:
when I type this in message it work ok :
Hi
my name is jack
.
but when I press enter after second sentence I get error and my program crash, I can't type like this:
Hi
My name is jack
this is message
.
thank you

When you type only enter the Scanner returns an empty String. When you try to get an empty String's first character with text.charAt(0), you go out of range and the StringIndexOutOfBoundsException is thrown.
A quick fix would be to check the length of the String before using charAt as follows:
if (text.length() > 0 && text.charAt(0) != '.')

The problem is that for an empty string, there is no 0th character, so text.charAt(0) fails.
Instead, you can use text.startsWith(".") to test for the first character (or first few characters), and text.isEmpty() to test for an empty input, i.e., when the user hits enter without writing any text first.
Also, since your second if condition is exactly the negation of the first, you can just use else here.

Add simple length check and continue if 0

Related

How to ask user for ONLY one word string input and produce error prompt in a try-catch block

EDIT: I figured it out! I got rid of the try-catch block because it just didn't work the way I wanted it to. The code below is my final one. Thank you to everyone who responded to this question.
I am trying to code a to-do list program. One function of this program is to search for the entries inside the string array. The user should only input a ONE WORD keyword so if the user inputs more than one word or none, a prompt should show telling the user to try again. The code I've written so far is inside a try-catch statement. Using next() scanner only takes the first word and disregards the rest when inputting a multiple-word keyword, instead of producing an Exception. Here is my code for it:
case 2:
String searchKeyword;
int success = 0;
while(success==0) {
System.out.print(">> Enter 1 keyword: ");
searchKeyword = sc.nextLine();
String splitSearchKeyword[] = searchKeyword.split(" ");
if (splitSearchKeyword.length == 1) {
if(Quinones_Exer2.searchToDoList(searchKeyword, todoList)==-1) {
System.out.println(">> No item found with that keyword!");
System.out.println();
}
else {
System.out.println(">> Found one item!");
System.out.println("("+(Quinones_Exer2.searchToDoList(searchKeyword, todoList)+1)+")"+" "+todoList[Quinones_Exer2.searchToDoList(searchKeyword, todoList)]);
System.out.println();
}
success++;
}
else {
System.out.println(">> Please input a single word keyword!");
System.out.println();
}
}
break;
}```
Use Scanner.nextLine() then split the supplied string. If the length of array is greater than 1 or the supplied string is empty then issue an invalid entry message and have the User enter the string over again:
while(tries2 == 0) {
searchKeyword = "";
while (searchKeyword.isEmpty()) {
System.out.println("Enter 1 keyword: ");
searchKeyword = sc.nextLine().trim();
if (searchKeyword.isEmpty() || searchKeyword.split("\\s+").length > 1) {
System.out.println("Invalid Entry! {" + searchKeyword
+ "You must supply a single Key Word!");
searchKeyword = "";
}
}
tries2++;
// ... The rest of your code ...
}
From the docs of Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
You would need to call next() again to get the the rest of the input.
Much simpler would be to use Scanner.nextLine() to get entire line and then use String.split() with whatever delimiter you are using to get an array of all inputted keywords.
Edit: Scanner.next(pattern) may do what you are looking for. It throws InputMismatchException if the input does not match provided pattern(regex). Example:
scanner.next("^[a-zA-Z]+$")
This requires the entire line to consist of lower and/or upper case letters and nothing else.

How to Test if Input String is Null in Java

So I created some code to check if the first letter of the word that the user enters (stored in the variable word) is a consonant or vowel. If it is neither it outputs saying it is neither. However, I am using nextLine() instead of next() to get input. I understand that next() will not take input until they enter a valid character besides a space, and I know that nextLine() will go to the else statement if they enter just spaces. However, in nextLine when the user just puts enter and does not enter any character, no spaces, the program crashes. I tried checking if the string was equal to null and then making it print out "test" if it was proven true, however for some reason whenever I press enter I still get an error. Below is my code:
import java.util.Scanner;
public class WordStart {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Please enter a word: ");
String word = in.nextLine();
String lowerWord = word.toLowerCase();
String x = lowerWord.substring(0,1);
String test = null;
String empty = new String();
boolean vowel = x.equals("a")||x.equals("e")||x.equals("i")||
x.equals("o")||x.equals("u");
boolean conc = x.equals("b")||x.equals("c")||x.equals("d")||x.equals("f")||
x.equals("g")||x.equals("h")||x.equals("j")||x.equals("k")||
x.equals("l")||x.equals("m")||x.equals("n")||x.equals("p")||
x.equals("q")||x.equals("r")||x.equals("s")||x.equals("t")||
x.equals("v")||x.equals("w")||x.equals("x")||x.equals("y")||
x.equals("z");
if(vowel){
System.out.printf("%s starts with a vowel.\n", word);
}
else if(conc){
System.out.printf("%s starts with a consonant.\n", word);
}
else if(word.equals("")){
System.out.println("testEmpty");
}
else if(word.isEmpty()){
System.out.println("testNull");
}
else{
System.out.printf("%s starts with neither a vowel nor a consonant.\n", word);
}
}
}
Basically, I am trying to check if the user just pressed enter without entering anything and call them out on it. What method, line of code would help me do that. I tried using word.equals(null), but the IDE said that it was never true. Thanks in advance.
The error code I get when I just press enter is as follows
run:
Please enter a word:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at WordStart.main(WordStart.java:8)
C:\Users\Jordan\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I think the problem lies with this line:
String x = lowerWord.substring(0,1);
If the string is empty (nextLine will never return a null string) it is impossible to take a substring. You should probably check that the string is > 0 characters long.
if(x.length > 0)
String x = lowerWord.substring(0,1);
Firstly note that word.equals("") and word.isEmpty() checks the same condition. So there is no need to use them both. To check whether is String null use if (word == null). Checking the null and the emptyness of the String should be the first one you do.
Secondly in case you skip the input (get the empty String ""), you get IndexOutOfBoundsException, because lowerWord.substring(0,1); has no chance to find that index.
So:
if (word != null && !word.isEmpty()) {
// ...
}
Just check if it is null
if(variable==null)
should suffice

NumberFormatException thrown by Integer.parseInt

Hey Im taking coding lessons at school but the teacher does not explain that well so we have to look for info online which I did, but I was not able to find the error in my code, can you help me please?
char end='s';
do{
System.out.println("Tipo de boleto");
char boleto = (char) System.in.read();
switch (boleto){
case 'a':
System.out.println("El boleto cuesta $120.00");
System.out.println("Otro boleto (s/n)?");
end = (char) Integer.parseInt(entrada.readLine());
continue;
case 'n':
System.out.println("El boleto cuesta $75.00");
System.out.println("Otro boleto (s/n)?");
end = (char) Integer.parseInt(entrada.readLine());
continue;
case 'i':
System.out.println("El boleto cuesta $60.00");
System.out.println("Otro boleto (s/n)?");
end = (char) Integer.parseInt(entrada.readLine());;
continue;
default:
System.out.println("Error" );
break;
}
}
while (end == 'n');
Exception
run: Tipo de boleto a El boleto cuesta $120.00 Otro boleto (s/n)?
Exception in thread "main" java.lang.NumberFormatException: For input string: "" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:592) at
java.lang.Integer.parseInt(Integer.java:615) at
asjidbhahsjksbd.Asjidbhahsjksbd.main(Asjidbhahsjksbd.java:16) Java Result: 1
BUILD SUCCESSFUL (total time: 7 seconds)
See, you are trying to parse "" as an Integer whichwill throw NumberFormatException. You have to check for null and isEmpty() in this order and then try to parse the string as an integer.
You are getting exception in this line , i think you are getting "" blank String from readLine() method
end = (char) Integer.parseInt(entrada.readLine());
So Do like this
String input=entrada.readLine();
if(input!=null && !input.equals(""))
{
end = (char) Integer.parseInt(input);
}
I suggest you to use google guava libraries which is having a utility function
Strings.isNullOrEmpty(inputString)//Checks String for both null and empty
Update
As #ajb suggested :
If you want to convert s and n into character than don't use your code snippet
instead of Parsing an Integer
Use
char c=input.charAt(0);
you should replace continue statement with a break. putting continue will skip the current iteration and the while condition will not be evaluated.
This does not do what you think it will:
end = (char) Integer.parseInt(entrada.readLine());
This line reads a string. It then assumes the string is a number, and determines the number. If the user actually enters "s" or "n", it throws an exception, because "s" and "n" are not numbers. The number is then treated as the ASCII value of a character. The result is that the loop will test whether the user types in the string "110", since 110 is the ASCII value of the character n.
There are several ways to fix this; here's one:
end = entrada.readLine().charAt(0);
This returns the first character of whatever line the user types in. This is a sloppy solution because it doesn't work if the user hits ENTER on an empty line (it will throw an exception). Better:
String answer = entrada.readLine();
if (answer.isEmpty()) {
end = 'n'; // treat an empty string like 'n'
} else {
end = answer.charAt(0);
}
Also, I think the while might be wrong. while (end == 'n') means the program will loop back if the user enters n, which I think is the opposite of what you want.
P.S. There are other errors that I didn't catch, that others have pointed out; using continue is wrong--use break to leave the switch statement. And reading one character with System.in.read() is a problem, because the user will type in a character, but the character won't get into the program until the user types ENTER, and then readLine() will get the rest of this first line, instead of asking for another line. But I usually don't use System.in.read() so I'm not completely sure what this does without trying it.

Java Skip Iteration 0

Im new at Java Console.
for (i=0;i<=noOfSP;i++)
{
System.out.println("NAME OF THE Plan #" + i + "?: 'Example input: 4GB' ");
nameOfPlan = scn.nextLine();
SubscriptionPlan subscriptionPlan = new SubscriptionPlan(nameOfPlan);
if ( !gsmProvider.addSubscriptionPlan(subscriptionPlan) )
{
System.out.println("Adding Error. Program Will Closing.");
System.exit(1);
}
}
In this codeblock I wanna read name. I read "noOfSP" from user type of Integer. But iteration 0 won't work? If noOfSP is 0, program skips for loop ? Why?
EDIT:
I edited inside the for loop. Okay but still can not read 0. iteration.
NUMBER OF SUBSCRIPTION PLANS ? : 'Example input: 1'
1
NAME OF THE Plan #0?: 'Example input: 4GB'
NAME OF THE Plan #1?: 'Example input: 4GB'
The 0. iteration is skipped ? Why?
Here is your solution. Change
nameOfPlan = scn.nextLine();
To
nameOfPlan = new Scanner(System.in).nextLine();
Why?
When you input any value and hit enter, a new-line character will be appended to the end of your input. in your case, when you press enter for the noOfSP value, a new-line character (/n) was appended by default.
Since you have use scn.nextInt() for noOfSP value (most probably), its only fetch the int, and there is still new-line characters (\n) left.
your first for loop iteration (iteration 0) fetch the \n thus, skip the scn.nextLine() in first iteration .
Note: you can also fix this by adding scn.nextLine(); just before your for loop:
....
scn.nextLine();
for (i=0;i<=noOfSP;i++){
.....
As for loop says i value should be less than noOfSP, that's why it skips the loop.
Change for loop to
for (i=0;i<=noOfSP;i++)
if i=0 and noOfSP is 0 at start, (0<0) will return false
use this instead:
for(i=0; i<=noOfSP;i++)

Novice programmer needs advice: "String index out of range" - Java

I'm pretty new to programming and I'm getting a error which I'm sure is a easy fix for more experienced people.
Here is what I have:
import java.io.*;
import java.util.Scanner;
public class ReadNamesFile
{
public static void main(String[] args) throws IOException {
// make the names.csv comma-separated-values file available for reading
FileReader f = new FileReader("names.csv");
BufferedReader r = new BufferedReader(f);
//
String lastName="unknown", firstName="unknown", office="unknown";
// get first line
String line = r.readLine();
// process lines until end-of-file occurs
while ( line != null )
{
// get the last name on the line
//
// position of first comma
int positionOfComma = line.indexOf(",");
// extract the last name as a substring
lastName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the first name as a substring
firstName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the office number as a substring
office = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+2);
//
//
//
// display the information about each person
System.out.print("\nlast name = "+lastName);
System.out.print("\t first name = "+firstName);
System.out.print("\t office = "+office);
System.out.println();
//
// get the next line
line = r.readLine();
}
}
}
Basically, it finds the last name, first name and office number in a .csv file and prints them out.
When I compile I don't get any errors but when I run it I get:
java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)
Before trying to do the office number part, the first two (last and first name) printed out fine but the office number doesn't seem to work.
Any ideas?
Edit: Thanks for all the posts guys, I still can't really figure it out though. Can someone post something really dumbed down? I've been trying to fix this for an hour now and I can't get it.
Let's work by example, what issues you have with your code.
Eg: line: Overflow,stack
{ length: 14 }
Taking your program statements line by line -
int positionOfComma = line.indexOf(","); // returns 9
lastName = line.substring(0,positionOfComma); // should be actually postionOfComma-1
Now lastName has Overflow. positionOfComma has 9.
line = line.substring(positionOfComma+1);
Now line has stack.
firstName = line.substring(0,positionOfComma);
Asking substring from 0 to 9. But stack is only of length 5. This will cause String index out of range exeception. Hope you understood where you are doing wrong.
From JavaDoc:
(StringIndexOutOfBoundsException) - Thrown by String methods to
indicate that an index is either negative or greater than the size of
the string.
In your case, one of your calls to .substring is being given a value that is >= the length of the string. If line #34 is a comment, then it's the line above #34.
You need to:
a) Make sure you handle the case if you DON'T find a comma (i.e. if you cannot find and extract a lastName and/or firstName string)
b) Make sure the value of "positionOfComma + N" never exceeds the length of the string.
A couple of "if" blocks and/or "continue" statements will do the trick nicely ;-)
You correctly find positionOfComma, but then that logic applies to the original value of line. When you remove the last name and comma, positionOfComma is no longer correct as it applies to the old value of line.
int positionOfComma = line.indexOf(",");
this line of code might not find a comma and then positionOfComma will be -1. Next you substring something with (0,-1) - eeek no wonder it gives StringIndexOutOfBoundsException. Use something like:
int positionOfComma = 0;
if(line.indexOf(",")!=-1)
{
positionOfComma = line.indexOf(",");
}
You do have to do lots of checking of things sometimes especially when the data is whacked :(
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
PS I'm sure someone clever can make my coding look shabby but you get the point I hope :)

Categories

Resources