I have been trying to fix this for a while now and I just can't seem to get it. I'm trying to get the phone number from the user so I can display it but when I get all the users info the error occurs. Any help would be appreciated. Thank you.
Here is the code:
import java.util.Scanner;
public class Event
{
public static double pricePerGuestHigh = 35.00;
public static double pricePerGuestLow = 32.00;
public static final int LARGE_EVENT_MAX = 50;
public String phone = "";
public String eventNumber;
private int guests;
private double pricePerEvent;
public void setPhone()
{
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Enter your phone number: ");
String phone = input.nextLine();
int len = phone.length();
for(int i=0; i<1; i++)
{
char c = phone.charAt(i);
if(Character.isDigit(c))
{
count++;
String ss = Character.toString(c);
phone = phone.concat(ss);
}
}
if(count != 10)
{
phone = "0000000000";
}
}
public String getPhone()
{
// The error occurs in this method
String ret = "(" + this.phone.charAt(0) + "" + this.phone.charAt(1)
+ "" + this.phone.charAt(2) + ")" + this.phone.charAt(3)
+ "" + this.phone.charAt(4) + "" + this.phone.charAt(5)
+ "" + this.phone.charAt(6) + "" + this.phone.charAt(7)
+ "" + this.phone.charAt(8) + "" + this.phone.charAt(9);
return ret;
}
public void setEventNumber()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the event number: ");
eventNumber = input.nextLine();
}
public void setGuests(int guests)
{
this.guests=guests;
if(isLargeEvent())
pricePerEvent = pricePerGuestHigh;
else
pricePerEvent = pricePerGuestLow;
}
public int getGuestsCount()
{
return guests;
}
public boolean isLargeEvent()
{
if(guests >= LARGE_EVENT_MAX)
{
return true;
}
else if(guests < LARGE_EVENT_MAX)
{
return false;
}
return isLargeEvent();
}
public String getEventNumber()
{
String ret1 = "Event Number: " + this.eventNumber;
return ret1;
}
public int getGuests(boolean largeEvent)
{
return guests;
}
}
The code where the error occurs has been marked with a comment.
The error means that you are trying to access the phone's character at an index that does not exists.
Precisely, your phone field is never set inside your code so it's an empty String.
Anyway, you should also fix the for loop by using the len variable:
int len = phone.length();
for(int i = 0; i < len; i++)
{
...
}
By doing that, you cannot concern about StringIndexOutOfBoundsException because now the for automatically traverse only the chars present in the String.
The StringOutOfBoundsException is thrown whenever you're attempting to access a character in the string that doesn't exist at the given index.
From the code you've provided it seems as though you're accessing an empty string in the method getPhone().
You can fix this by first checking if the string is empty with phone.isEmpty().
public String getPhone() {
if (phone == null || /*this.*/phone.isEmpty()) {
// Handle the error accordingly.
return null; // example
}
String ret = "(" + this.phone.charAt(0) + "" + this.phone.charAt(1)
+ "" + this.phone.charAt(2) + ")" + this.phone.charAt(3)
+ "" + this.phone.charAt(4) + "" + this.phone.charAt(5)
+ "" + this.phone.charAt(6) + "" + this.phone.charAt(7)
+ "" + this.phone.charAt(8) + "" + this.phone.charAt(9);
return ret;
}
While we're at it, I'd recommend not using string concatenation, as this will produce a large amount of overhead.
Instead, use Java's string formatting.
This will not only increase the readability of your code, but it will (as mentioned before) reduce overhead, because strings in Java are immutable.
To make your code work you should make new local var (for example inputPhone) and than change phone var of Event object. Also you should change condition in for loop.
public void setPhone()
{
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Enter your phone number: ");
String inputPhone = input.nextLine();
int len = inputPhone.length();
for(int i=0; i<len; i++)
{
char c = inputPhone.charAt(i);
if(Character.isDigit(c))
{
count++;
String ss = Character.toString(c);
phone = phone.concat(ss);
}
}
if(count != 10)
{
phone = "0000000000";
}
}
Related
I have a string s to which I want to append another string s1 at the specified position.
String s = "17.4755,2.0585,23.6489,12.0045";
String s1=",,,,"
Now I want to add the string s1 after the n-th occurrence of "," character.
I have just started learning Java.
You can use the following method:
public String insert(int n, String original, String other) {
int index = original.indexOf(',');
while(--n > 0 && index != -1) {
index = original.indexOf(',', index + 1);
}
if(index == -1) {
return original;
} else {
return original.substring(0, index) + other + original.substring(index);
}
}
Working with Strings directly is not worth the trouble.
One easy way would be to turn your String into a List and manipulate that.
public void test() {
String s = "17.4755,2.0585,23.6489,12.0045";
// Split s into parts.
String[] parts = s.split(",");
// Convert it to a list so we can insert.
List<String> list = new ArrayList<>(Arrays.asList(parts));
// Inset 3 blank fields at position 2.
for (int i = 0; i < 3; i++) {
list.add(2,"");
}
// Create my new string.
String changed = list.stream().collect(Collectors.joining(","));
System.out.println(changed);
}
Prints:
17.4755,2.0585,,,,23.6489,12.0045
I think this is what you want
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = "17.4755,2.0585,23.6489,12.0045";
String s1=",,,,";
System.out.println("Enter Nth Occurrence");
try {
int n = scanner.nextInt();
long totalOccurrence = 0;
if (n != 0) {
totalOccurrence = s.chars().filter(num -> num == ',').count();
if (totalOccurrence < n) {
System.out.println("String s have only " + totalOccurrence + " symbol \",\"");
} else {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ',') {
count++;
if (count == n) {
String resultString = s.substring(0, i) + s1 + s.substring(i, s.length());
System.out.println(resultString);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Wrong input");
}
}
}
Output :
1. Enter Nth Occurrence
5
String s have only 3 symbol ","
2. Enter Nth Occurrence
2
17.4755,2.0585,,,,,23.6489,12.0045
I'm creating a program which makes the given input string into number so that input will be coded. But I'm running into a NumberFormatException as soon as the input string gets too long. I can't see how I can fix this.
Note that I have to get substrings from the given string input, turn them into numericValues then get the sum of these two strings as an answer.
Code:
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "youuu + are = gay"; //as soon as the substrings before = sign are
//longer than 5 characters the exception occurs
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count = 0;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c);
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = count - 1;
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Integer.parseInt(first) + Integer.parseInt(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("Yhe s6na maksimaalne pikkus on 18 t2hem2rki ");
}
}
return words;
}
Integers in Java (as in many languages) are limited by a minimum and maximum value.
More information on this can be found here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
You could give a meaningful error in the catch-block
You did not enter a valid 32-bit Integer value.
Or you could switch to something like a BigDecimal which can hold bigger values: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
(watch out: BigDecimal works very different from a normal int, so read the documentation wisely, and Google for examples if necessary)
EDIT: you can parse it to Long as well, if you want that: Long.parseLong(INPUT, 10);. That way you extend the limit to 64-bit.
I am trying to get it to return a compressed word. For example, reaction should be #act$. But it is getting returned as react$. I feel like my issue is not including the original word in the return statement. Can anyone help? Thanks!
public static String compress (String word) {
String newWord = "";
int the = word.indexOf("the");
if (the >= 0) {
newWord = word.substring(0,the) + "&" + word.substring(the+3);
}
int ion = newWord.indexOf("ion");
if (ion >= 0) {
newWord = newWord.substring(0,ion) + "$" + word.substring(ion+3);
}
int ing = newWord.indexOf("ing");
if (ing >= 0) {
newWord = newWord.substring(0,ing) + "~" + word.substring(ing+3);
}
int an = newWord.indexOf("an");
if (an >= 0) {
newWord = newWord.substring(0,an) + "#" + word.substring(an+2);
}
int re = newWord.indexOf("re");
if (re >= 0) {
newWord = newWord.substring(0,re) + "#" + word.substring(re+2);
}
int con = newWord.indexOf("con");
if (con >= 0) {
newWord = newWord.substring(0,con) + "%" + word.substring(con+3);
}
return newWord;
}
A compressed version also:
public static String compress(String word) {
word = word.replace("the", "&");
word = word.replace("ion", "$");
word = word.replace("ing", "~");
word = word.replace("an", "#");
word = word.replace("re","#");
word = word.replace("con","%");
return word;
}
You're mixing up your uses of newWord and word in a confusing way. If the first if clause doesn't fire, newWord will still be an empty string and none of the other conditions will fire. On the other hand, if newWord does get set to something, you still go on using word substrings, in ways that don't make any sense.
You would be better off just using one variable through the whole method.
public static String compress(String word) {
int the = word.indexOf("the");
if (the >= 0) {
word = word.substring(0,the) + "&" + word.substring(the+3);
}
int ion = word.indexOf("ion");
if (ion >= 0) {
word = word.substring(0,ion) + "$" + word.substring(ion+3);
}
int ing = word.indexOf("ing");
if (ing >= 0) {
word = word.substring(0,ing) + "~" + word.substring(ing+3);
}
int an = word.indexOf("an");
if (an >= 0) {
word = word.substring(0,an) + "#" + word.substring(an+2);
}
int re = word.indexOf("re");
if (re >= 0) {
word = word.substring(0,re) + "#" + word.substring(re+2);
}
int con = word.indexOf("con");
if (con >= 0) {
word = word.substring(0,con) + "%" + word.substring(con+3);
}
return word;
}
Note also that, written this way, you can only use each replacement once per word: if you have "thethe" you will compress it to "&the", not "&&". If you want use replacements multiple times, you would have to use a loop. Or, easier still, use String.replace.
import java.util.Scanner;
class PhoneInfo {
String name;
String phoneNumber;
String birth;
public PhoneInfo(String name, String num, String birth) {
this.name = name;
phoneNumber = num;
this.birth = birth;
}
public PhoneInfo(String name, String num) {
this.name = name;
phoneNumber = num;
this.birth = null;
}
public void showPhoneInfo() {
System.out.println("name : " + name);
System.out.println("phone : " + phoneNumber);
if (birth != null)
System.out.println("birth : " + birth);
System.out.println("");
}
}
class PhoneBookManager {
final int MAX_CNT = 100;
PhoneInfo[] infoStorage = new PhoneInfo[MAX_CNT];
int curCnt = 0;
public void inputData() {
System.out.println("Start Data Entry..");
System.out.print("Name : ");
String name = MenuViewer.keyboard.nextLine();
System.out.print("Phone Number : ");
String phone = MenuViewer.keyboard.nextLine();
System.out.print("Date Of Birth : ");
String birth = MenuViewer.keyboard.nextLine();
infoStorage[curCnt++] = new PhoneInfo(name, phone, birth);
System.out.println("Data Entry is Finished. \n");
}
public void searchData() {
System.out.println("Data Search Begins.");
System.out.print("Name : ");
String name = MenuViewer.keyboard.nextLine();
int dataIdx = search(name);
if (dataIdx < 0) {
System.out.println("The Data does not exist. \n");
} else {
infoStorage[dataIdx].showPhoneInfo();
System.out.println("Data Search is finished. \n");
}
}
public void deleteData() {
System.out.println("Data delete starts..");
System.out.print(" Name : ");
String name = MenuViewer.keyboard.nextLine();
int dataIdx = search(name);
if (dataIdx < 0) {
System.out.println("Data does not exist. \n");
} else {
//Begin of code for explanation
for (int idx=dataIdx;idx<(curCnt-1);idx++)
infoStorage[idx]=infoStorage[idx + 1];
curCnt--; //Clear Explanation would be great!//
//End of code for explanation
System.out.println("Data Deletion Complete. ");
}
}
private int search(String name) {
for (int idx = 0; idx < curCnt; idx++) {
PhoneInfo curInfo = infoStorage[idx];
if (name.compareTo(curInfo.name) == 0)
return idx;
}
return -1;
}
}
This part is a real confuser for me, an obstacle in my java learning experience it would be great if one can explain this to me like I am less than a 10 year old. I have such a vague idea on how this is operating, therefore baby step by step explanation from experts would be a great source of learning for me!
for (int idx=dataIdx;idx<(curCnt-1);idx++)
infoStorage[idx]=infoStorage[idx + 1];
curCnt--;
The piece of code that you want/need an explanation for:
for (int idx=dataIdx;idx<(curCnt-1);idx++)
infoStorage[idx]=infoStorage[idx + 1];
curCnt--;
//adding this line as well
System.out.println("Data Deletion Complete. ");
The code above is meant to remove an item in the array:
for (int idx=dataIdx;idx<(curCnt-1);idx++)
//passing the elements in the array to a previous position
infoStorage[idx]=infoStorage[idx + 1];
Note that this for loop doesn't have any braces, so it only affects the statement next to it. It is better to write it as:
for (int idx=dataIdx;idx<(curCnt-1);idx++) {
//passing the elements in the array to a previous position
infoStorage[idx]=infoStorage[idx + 1];
}
For better code readability.
After the for loop execution, the line below decreases the current array size handler by 1:
curCnt--;
After item removal from the array, showing a nice message to user:
System.out.println("Data Deletion Complete. ");
Note that ++ and -- operators affect the current value of the variable: the former increases its value and the latter decreases it. For example, this code:
idx++
Is similar to write
idx = idx + 1;
More info on this:
Java Tutorials: Operators
After parsing a webpage i have found this line
"JANATAMF 7.30 -0.20 -2.67% 1STBSRS 80.00 -3.60 -4.31% 1STPRIMFMF 12.90 -0.80 -5.84% 6THICB 40.60 -2.50 -5.80% 8THICB 50.00 -1.30 -2.53% ABB1STMF 9.90 0.30 3.13% ACI 188.00 -5.90 -3.04% ACIFORMULA 82.70 0.50 0.61%"
now i want to find the corresponding integer value for any input such as
if i enter an input JANATAMF it will individually print 7.30 -0.20 -2.67%
i ve written a code but it does not look good..
public void stringfinder(String linktext,String input) throws NumberFormatException
{
try
{
if(linktext!=null)
{
String finalstr=linktext;
//System.out.print(finalstr);
int inplen=input.length();
if(finalstr.contains(input)) //CHECK THE USER INPUT IS IN STRING OR NOT WHICH RETURN BOOLEAN
{
//System.out.println("found");
int index=finalstr.indexOf(input); //FIND THE INDEX OR STARTING POINT OF THE STRING
//System.out.print(index);
int stpr=index+inplen+1; //AS WE VE TO PRINT THE NEXT STRING FROM THE INPUT STRING
//WE ADD THE STARTING POINT OF THE INPUT STRING AND THE LENGTH
//OF THE INPUT STRING
//int first=0;
int i=0;
String x="" ;
String ary[]=new String[10];
while(finalstr.charAt(stpr)!=' ' ) //PRINT UNTIL FIND A GAP
{
//System.out.print(finalstr.charAt(stpr));
Character c=new Character(finalstr.charAt(stpr));
String s=c.toString(c);
ary[i]=s;
x=x+ary[i];
i++;
stpr++;
//first++;
}
//System.out.print(x);
String yo=x;
System.out.print(yo);
//double d = Double.valueOf(yo.trim()).doubleValue();
/*int secstpr=stpr+1;
int second=0;
while(finalstr.charAt(secstpr)!=' ')
{
System.out.print(finalstr.charAt(secstpr));
secstpr++;
second++;
}*/
//System.out.print(second);
}
}
}
so plz help...
This is what #kev was referring to:
public String stringfinder(String linktext, String input) {
String [] inputSplits = input.split("\\s+");
for (int i = 0; i < inputSplits.length; i += 4) {
if (inputSplits[i].equals(linktext) {
return inputSplits[i + 1] + " " + inputSplits[i + 2]
+ " " + inputSplits[i + 3];
}
}
return "";
}
This will return the string you were searching for. Still I would suggest that instead you concatenate the strings here: return inputSplits[i + 1] + " " + inputSplits[i + 2] + " " + inputSplits[i + 3]; you interpret them more cleverly (e.g. construct numbers).