How to sum up user's input in arraylist? - java

I am trying to make a program that reads integers from the user and adds them to a list. This ends when the user enters 0. The program then prints the sum on the list.
My code works but the problem is the sum value does not add up correctly
public class Main {
private static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
ArrayList<Integer> test1 = new ArrayList<Integer>();
System.out.println("Enter multiple numbers"); //if user enters =0; loop ends
while (input.nextInt() != 0) {
test1.add(input.nextInt());
input.nextLine();
}
int total = 0;
for(int x : test1){
total+=x;
}
System.out.println(total);
}
}

You are only storing every third value in your loop. This
while (input.nextInt() != 0) {
test1.add(input.nextInt());
input.nextLine();
}
should be something like
int value;
while ((value = input.nextInt()) != 0) {
test1.add(value);
}
or
while (input.hasNextInt()) {
int value = input.nextInt();
if (value == 0) {
break;
}
test1.add(value);
}

Related

Take integer inputs till the user enters 0 and print the sum of all numbers (HINT: while loop) (coding language:- JAVA)

IN this problem we have to print the sum of all the numbers until the user enters zero.
my attempt:
import java.util.Scanner;
public class printsum_until_enter0 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
//int count = 0;
int x = in.nextInt();
while (x >0) {
if (x > 0) {
sum = sum + x;
System.out.println(sum);
x--;
} else {
System.out.println("no data was entered");
}
x--;
}
}
}
it runs infinitly before writing X--...but now it takes only one input and after that it is executed...but it supposed to execute after entering 0 and sum of all the numbers before entering 0. But it is not happeing.Any solution guys...Code in java..
Your problem is that you only ask the user for input once. What you want to do is move the scanner.nextInt part somehow into your loop. In java there is a concept called do while loop which executes the loop body first and then checks the loop condition if it should be repeated. If you do not want to use a do while loop you can use a while true loop to check if the input was 0 and exit. Notice also how x needs to be initialised before the function body to be recognized by the while statement
Unfortunately, I did not get why you decreased x in your code. Let me know if I misunderstood your question or you have any more questions
import java.util.Scanner;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int x = 0;
do {
System.out.println("Please insert a number: ");
x = in.nextInt();
// If x is 0 it wont change the sum
sum += x;
System.out.println(sum);
} while (x > 0);
System.out.println("no data was entered");
}
}
Fixed your code
package test1;
import java.util.Scanner;
public class printsum_until_enter0 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int x = in.nextInt();
while (x >0) {
if (x > 0) {
sum = sum + x;
} else {
System.out.println("no data was entered");
}
x = in.nextInt();
}
System.out.println(sum);
}
}
do {
x = in.nextInt();
if(x > 0) {
sum += x;
}
} while(x > 0)

How to find max number and occurrences

So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .
my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.
But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .
package myjavaprojects2;
import java.util.*;
public class Max_number_count {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int count = 0;
int max = 1;
System.out.print("Enter a Integer:");
int userInput = input.nextInt();
while ( userInput != 0) {
if (userInput > max) {
int temp = userInput;
userInput = max;
max = temp;
} else if (userInput == max) {
count++ ;
}
System.out.println("The max number is " + max );
System.out.println("The count is " + count );
}
}
}
So how do you take multiple inputs from the user on the same line .
You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.
int userInput = input.nextInt();
while ( userInput != 0) {
//all above logic
userInput = input.nextInt();
}
The code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0, count = 0, num;
System.out.println("Enter numbers:-");
while ((num = sc.nextInt()) != 0) {
if (num > max) {
max = num;
count = 1;
} else if (num == max) {
count++;
}
}
System.out.println("\nCount of maximum number = "+count);
}
}
And you don't have to use ArrayList or Array. Just keep inputting numbers till you get 0.
You can implement this with a single loop. The traditional concise pattern for doing so involves the fact that assignment resolved to the value assigned. Thus your loop can use (x = input.nextInt()) != 0 to terminate (handling exceptions, and non-integer input left as an exercise for the reader). Remember to display the max and count after the loop and reset the count to 1 when you find a new max. Also, I would default max to Integer.MIN_VALUE (not 1). That leaves the code looking something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Integer:");
int count = 0, max = Integer.MIN_VALUE, userInput;
while ((userInput = input.nextInt()) != 0) {
if (userInput > max) {
max = userInput;
count = 1;
} else if (userInput == max) {
count++;
}
}
System.out.println("The max number is " + max);
System.out.println("The count is " + count);
}

How can I define a char variable within a method?

I'm attempting to write a loop, that when the user inputs Y, the loop continues, and when the user inputs N, the loop stops. However, when I try to assign the variable I get the error "Cannot convert from void to char" I'm obviously messing up somewhere along the line but I'm not sure where.
import java.util.Scanner;
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
char ans = System.out.print("Would you like to input another value? (Y or N)? ");
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
} ```
You're assigning ans to the result of System.out.print() which is a void method.
Instead, create the prompt beforehand and use the Scanner to take the input:
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
// New Prompt
System.out.print("Would you like to input another value? (Y or N)? ");
// Take input and set ans
char ans = input.next().charAt(0);
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
}

JAVA : How do I input a ( < 0 ) to break the code?

2 weeks in. I need to break the while loop with a negative integer but I've been unable to implement it successfully. This is my original code before I editted left and right to no avail. The values in Print are outside the loop.
public class AssignmentQuestion2 {
public static void main(String[] args) {
//write your code here
ArrayList<Integer> rainfall = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Please input rainfall(Input negative value to exit)");
while (in.hasNextInt()) {
if (in.hasNextInt()) {
rainfall.add(in.nextInt()); //how to input into array
System.out.println(calculateAverage(rainfall)); //average
System.out.println(findSmallest(rainfall)); //smallest input
System.out.println(findLargest(rainfall)); //largest input
} else {
in.close();
}
}
}
You can break a loop using the (aptly named) break statement:
int r;
while ((rainfall != null)) {
if (in.hasNextInt()) {
r = in.nextInt();
if (r < 0) {
break;
}
rainfall.add(r); //how to input into array
System.out.println(calculateAverage(rainfall)); //average
System.out.println(findSmallest(rainfall)); //smallest input
System.out.println(findLargest(rainfall)); //largest input
}
}

I have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

Categories

Resources