Java Initialization Error -


double pullprice(string input){         if(input.length() < 3){             system.out.println("error: 02; invalid item input, valid example: enter code here'milk 8.50'");             system.exit(0);         }         char[] inputarray = input.tochararray();         char[] itempricearray;         double price;         boolean numval = false;         int numcount = 0;         for(int = 0; <= inputarray.length-1; ++){             //checking if need add char char array of price             if(numval == true){                 //adding number price array                 itempricearray[numcount] = inputarray[i];                 numcount++;             }             else{                 if(inputarray[i] == ' '){                     numval = true;                     //initializing price array                     itempricearray = new char[inputarray.length - i];                 }                 else{                  }             }           }         price = double.parsedouble(string.valueof(itempricearray));         return price;     } 

problem: attempting pull sequence of chars after white space between 'milk 8.50' input. initialization error occurs because initializing char array inside if else statement initialize array if finds whitespace.

question: since don't know char count number until find whitespace there way can initialize? compiler not trust me initialize before calling array.

also, if missing or there better ways code of please let me know. in java data structures class , learning fundamental data structures focus on efficiency , modularity @ same time. have pullprice function same thing pulls item name. combine these don't have reuse same code both can return items same datatype unless create class. unfortunately exercise use 2 arrays since practicing how use adt bags. appreciated?

try this:

double pullprice(string input) {    try    {       // instantiate new scanner object, based on input string       scanner scanner = new scanner(input);       // skip product (eg "milk")       string prod = scanner.next();       // , read price(eg 8.5)       double price = scanner.nextdouble();       // should close scanner, free resources...       scanner.close();       return price;    }    catch (nosuchelementexception ex)    {       system.out.println("error: 02; invalid item input, valid example: enter code here 'milk 8.50'");       system.exit(0);    }  } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -