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.

Member Avatar for ztini

Although I disagree with "someone", using Integer or String is suitable in this case.

System.out.print("Value: ");
		int value = new Scanner(System.in).nextInt();
		
		int sum = 0;
		while (value > 0) {
			sum += value % 10;
			value /= 10;
		}
		
		System.out.println(sum);
System.out.print("Value: ");
		String value = new Scanner(System.in).next();
		
		int sum = 0;
		for (char i : value.toCharArray()) 
			sum += Integer.parseInt(Character.toString(i));

		System.out.println(sum);
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.