0

java

The program will keep asking the user to insert a number until he writes "stop" or "Stop" then the loop will break and the sum of the numbers he'd inserted will be printed out. Questions are how to convert a whole list of strings to integers and how can i get the sum of the numbers in the list. i came this far: import java.util.ArrayList; import java.util.Scanner; public class loopStop { public static void main(String[] args) { while(true) { ArrayList<String> choices = new ArrayList<>() ; System.out.println("\nInsert a number!"); Scanner x = new Scanner(System.in); String inp = x.nextLine() ; choices.add(inp) ; if(inp.equals("stop")){ break; for(String a : choices){ System.out.println((int)a); } } } } }

15th Sep 2022, 4:02 PM
Lenoname
5 odpowiedzi
+ 1
Lenoname Add try catch block when you add in list https://code.sololearn.com/cDz7p1oh3W7k/?ref=app
15th Sep 2022, 4:56 PM
A͢J
A͢J - avatar
+ 2
Lenoname Simple make list of Integer Convert input values to integer when Input is not 'stop' or 'Stop' Add converted input to list
15th Sep 2022, 4:07 PM
A͢J
A͢J - avatar
+ 2
Lenoname Also there are some correction in your code Make Scanner object outside while loop Use equalsIgnoreCase method Declare and Initialise list outside the loop -------- import java.util.*; public class LoopStop { public static void main(String[] args) { List<Integer> choices = new ArrayList<>(); System.out.println("Insert a number!"); Scanner x = new Scanner(System.in); while(true) { String inp = x.nextLine(); if(inp.equalsIgnoreCase("stop")) break; choices.add(Integer.parseInt(inp)); } int sum = 0; for(Integer i : choices) sum += i; System.out.print(sum); } }
15th Sep 2022, 4:20 PM
A͢J
A͢J - avatar
0
now choices.add() wont accept a string to the list of integers import java.util.ArrayList; import java.util.Scanner; public class loopStop { public static void main(String[] args) { while(true) { ArrayList<Integer> choices = new ArrayList<>() ; System.out.println("\nInsert a number!"); Scanner x = new Scanner(System.in); String inp = x.nextLine() ; choices.add(inp) ;<----------new problem if(inp.equals("stop")){ break; } else if(!inp.equals("stop")){ } } } }
15th Sep 2022, 4:28 PM
Lenoname
0
import java.util.ArrayList; import java.util.Scanner; public class loopStop { public static void main(String[] args) { ArrayList<Integer> choices = new ArrayList<>() ; Scanner x = new Scanner(System.in); while(true) { System.out.println("\nInsert a number!"); String inp = x.nextLine() ; if(inp.equalsIgnoreCase("stop")){ break; choices.add(Integer.parseInt(inp)) ;<-------------says"java: incompatible types: java.lang.String cannot be converted to java.lang.Integer" } int sum = 0 ; for(Integer i : choices){ sum += i ; System.out.println(sum); } } } }
15th Sep 2022, 4:44 PM
Lenoname