I created a console program in jcreator (java) which asks the user to enter a number in string and converts that string value into char array and then converts each char array into an integer which I also stored each as an array and then adds all the value from integer array and prints the total on the screen. Someone says its not the solution he is looking for and that I shouldnt use string and I need to focus on the integer value. Is there any other way of doing this as unlike my program? if there is, can you show me the code you have used? thank you.

Recommended Answers

All 4 Replies

if u want to convert string to int

String s = "2";

int x = Integer.parseInt(s);

but u could directly get the int value using nextInt

Scanner sc = new Scanner(System.in);
int x = sc.nextInt(); //edited to assign sc.nextInt() to int x

hope this helps.

give me a sample working program. does that break the string digits into every single integer value? for example, i entered 123 the output should be 6. im trying to do it in a for loop while storing the nextint value to an array and i dont get any gud result

first change the string to integer. that is

Scanner sc = new Scanner(System.in);
String st = sc.nextLine(); 
int x = Integer.parseInt(st);

//then goin to find the total of the sum of the individual digits. 
int total=0;

  total += x%10;
  x = x/10;

its just simple maths. what happens here is, say x=123 and when x is divided by 10 the answer is gonna be 12 and 3 the reminder. so x%10 gives u the reminder. and then u r adding the reminder digits to the total and u r repeating it until the last digit.

hope this helps.

yes it does! this makes sense. i was thinking of storing it into an integer array. thanks a lot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.