Changing input variables in a java loop - java

I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
Scanner in = new Scanner (System.in);
System.out.println("Please enter ten numbers:");
int[] inputs = new int[10];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
//Process
totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
It's not great, but it's the best I have so far. Please help?

You don't need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += = in.next(); // sum = sum + in.next();
}
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.

You can achieve that in two ways, either inside the loop itself just add the number or if you need to keep track of them for later just add them to the array.
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
String total;
Scanner in = new Scanner (System.in);
int numOfInputValues = 10;
System.out.println("Please enter ten numbers:");
int[] inputs = new int[numOfInputValues];
for (int i = 0; i < numOfInputValues; ++i)
{
// Append to array only if you need to keep track of input
inputs[i] = in.next();
// Parses to integer
total += in.nextInt();
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}

First of all, your class should be in CamelCase. First letter is always in capital letter.
Second, you don't need an array to save those numbers.
Third you should make a global variable that you can change with ease. That is a good practice.
And you should always close stream objects like Scanner, because they leak memory.
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
int numberQuantity = 10;
int totalNum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers:");
for (int i = 0; i <= numberQuantity; i++) {
totalNum += in.nextInt();
}
in.close();
System.out.println(totalNum);
}
}

So the simplest answer I found is:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
int totalNum, num1;
totalNum = 0;
for (int numbers = 1 /*declare*/; numbers <= 10/*initialise*/; numbers ++/*increment*/)
{
num1 = Integer.parseInt(JOptionPane.showInputDialog("Input any number:"));
totalNum = totalNum + num1;
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);

Try this way I only re-edit your code:
import javax.swing.*;
public class InputNums {
public static void main(String[] args) {
int total = 0;
for (int i = 0, n = 0; i < 10;) {
boolean flag = false;
try {
n = Integer.parseInt(JOptionPane
.showInputDialog("Input any number:"));
} catch (NumberFormatException nfe) {
flag = true;
}
if (flag) {
flag = false;
JOptionPane.showMessageDialog(null,
"Invalid no Entered\nEnter Again...");
continue;
}
total += n;
i++;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
}

Related

Never ending for loop with user input

I am new to java and have just learned how to use user input. I have a for loop that goes through 10 times with user input to ask for a number. If the number is invalid, it should print "Invalid number" and not count towards the increasing for loop. Instead, it just loops forever saying 'Invalid number'.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);
for(int i = 1; i<=10; i++){
System.out.println("Enter number #" + i + " ");
boolean validInt = scanner.hasNextInt();
if(validInt){
int num = scanner.nextInt();
sum += num;
} else{
System.out.println("Invalid Number");
i--;
}
}
System.out.println("Sum was " + sum);
scanner.close();
}
}
The problem is you are updating the iterator i at 2 places.
The better way is to update it according to the condition.
I would also suggest you to make use of wrapper classes for safe integer conversions and handle the exceptions properly like done in the following code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);
for(int i = 1; i<=10; ){
System.out.println("Enter number #" + i + " ");
String input = scanner.nextLine();
try{
int num = Integer.parseInt(input);
sum += num;
i++; // If input is a valid integer, then only update i
}catch(NumberFormatException e){
System.out.println("Invalid Number");
}
}
System.out.println("Sum was " + sum);
scanner.close();
}
}
I think you also can tweak the code using hasNextInt() directly in the while loop.
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
sum += num;
}
I needed to add a
scanner.nextLine();
After the if and else statement to clear the scanner in both situations.

Issue: Reading 10 different marks into my marks variable. FOR loop

import java.util.*;
public class loops
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in).useDelimiter("\n");
for (int i = 0; i <= 9; i++)
{
System.out.print("Enter your mark: ");
int marks = input.nextInt();
}
int marks = + input.nextInt();
int totalmarks = marks / 10;
System.out.println("The class average was:"+ totalmarks + ".");
}
}
The question is not clearly asked but according to my interpretation, the problem is to add all the input marks and give the average, so declare a sum variable with initial value 0 and add all the marks coming as input and take the average.
import java.util.*;
public class loops
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in).useDelimiter("\n");
int sum=0;
for (int i = 0; i <= 9; i++)
{
System.out.print("Enter your mark: ");
int marks = input.nextInt();
sum=sum+marks;
}
int totalmarks = sum / 10;
System.out.println("The class average was:"+ totalmarks + ".");
}
}

I am trying to write a program that allows me to input multiple integers, but it won't allow me to enter in my set of integers

My code won't allow me to enter in multiple integers to where it can then compute the sum, the count of integers, the minimum, and the sum of positive even integers. I am not sure if I need another method or if im calling for the wrong things.
import java.util.Scanner;
public class Assignment2 {
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
//when code reads 0, code terminates
int[] numbers = new int[4];
for(int i=0; i<4; i++){
numbers[i] =sc.nextInt();
}
while(!(n==0)){
sum += n;
n = input.nextInt();
}
class SumOfValues {
public int sum(int...vals){
int sum=0;
for (int val : vals) {
sum+= val;
}
return sum;
}
}
class CountingInts{
public void main(String[] args){
Scanner input=new Scanner(System.in);
int count=0;
System.out.print("Numbers: ");
while (input.hasNextInt()){
input.nextInt();
count++;
}
System.out.print(count);
input.close();
}
}
int sumPositive = 0;
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers );
}
}
It looks like you are an absolute beginner, so I'd recommend not dealing with functions and classes and all that, and just write everything linearly. I'm not sure why you have all those functions, classes and variables, but to help you, this is probably the simplest way to achieve what you are trying to do.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int sum = 0, minNumber = 0, nCount = 0, countEvenIntegers = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int input = sc.nextInt();
if (input == 0) {
break;
}
sum += input;
nCount += 1;
}
System.out.println("The minimum integer is " + minNumber);
System.out.println("The count of integers is " + nCount);
System.out.println("The sum of positive integers is " + sum);
System.out.println("The count of even integers in the sequence is " + countEvenIntegers);
}
}
Note that I've not added the minimum interger and count of even intergers for you to complete.
Not quite sure what you are doing in your code since you are not doing any operations on the variables you are outputting, and thus should not expect the output to be any other than 0.
Also, your inner classes are really weird.
Here is an example (based on your code) that does what you want. Plenty of ways of achieving your goal, but I think this is simple enough:
import java.util.Scanner;
import java.util.*;
public class Assignment2{
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0, sumPositive = 0;
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while(true) {
int i = sc.nextInt();
if(i == 0) {
break;
}
numbers.add(i);
}
if(numbers.size() > 0) {
minNumber = numbers.get(0);
}
for (int number : numbers) {
sum += number;
if(minNumber > number) {
minNumber = number;
}
if(number % 2 == 0) {
countEvenIntegers++;
}
if(number > 0 ) {
sumPositive += number;
}
}
nCount = numbers.size();
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers + "\nThe total sum is " + sum);
}
}

I am getting error messages concerning my coding. I know Scanf is not a java function, so I am hoping to get help converting it

I know that scanf is not a java function, so i'm hoping someone can help me to understand how to convert this. Research on this topic is difficult to piece together.
This is my code:
import java.util.Scanner;
public class Average {
Scanner Scanner = new Scanner (System.in);
int main (){
int counter;
int number;
int total;
float average;
total = 0;
counter = 0;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
While (number != 0) {
total = total + number;
counter = counter + 1;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
}
if(counter != 0) {
average = (float) total / counter;
System.out.println("Average is %.2f\n", average);
} else {
System.out.println("No valid numbers have been entered.");
return 0;
}
}
}
use input like this`
public class seting{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);`
int total = 0;
System.out.printlnln("Enter the value of total :");
total = scan.nextInt(); // use integer input
}
}
You cannot use the same name for the object as for the class. Change Scanner initialization as follows:
Scanner scanObj = new Scanner(System.in);
Replace all your scanf statements with the below:
number = scanObj.nextInt();
These are the changes done to your code:
import java.util.Scanner;
public class one {
public static void main(String[] args) {
Scanner Scanner = new Scanner (System.in);
int counter;
int number = 1;
int total;
float average;
total = 0;
counter = 0;
while(number != 0){
System.out.println("Enter the number 0 to end: ");
number = Scanner.nextInt();
System.out.printf("%d", number);
total = total + number;
counter = counter + 1;
}
if(counter != 0){
average = ((float)total /(float)counter);
System.out.printf("Average is %.2f\n", average);
}
else{
System.out.println("No valid numbers have been entered.");
//return 0;
}
}
}
First the Scanner takes the value the user entered. number = Scanner.nextInt(); This must be done inside your while loop since its the one that check the condition.
The next thing I changed was average = (float) total / counter;
This casts the total value only to a float. use brackets to both ends.
average = ((float)total /(float)counter); like this

While loop not working

Hi I am fairly new to java and trying to familiarize myself to it by doing some exercises online.
How do i properly code the while loop so that everytime the user input is wrong it asks the same question again and does not proceed to the next line of code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
boolean checker = true;
while (checker){
for (int i = 0; i < entries; i++){
int input;
int addToList;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
grade.add(input);
if (input >= 0 && input<= 100) {
}else {
System.out.println("invalid input try again..");
checker = false;
}
}
}
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade){
sum+= grades;
}
mean =(double)sum/count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
Your logic is backwards. You want the loop to continue if the input is incorrect. There are two ways to fix this:
Change while(checker) to while(!checker)
Change checker=false to checker=true after printing the error message. And set checker=false in the if branch.
It might help if you change the name of your checker variable to something that reads more directly. For example isInputCorrect reads very nicely when you write while(!isInputCorrect) and it also makes it more clear what the values of true and false represent.
try this :
boolean checker = true
for(int i=0;i< entries;i++){
int input;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
while(checker){
if(input >= 0 && input<= 100){
grade.add(input);
checker = false;
}else{
System.out.println("invalid input try again..");
}
}
checker = true;
}
You could try this
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
for (int i = 0; i < entries; i++) {
int input;
do{
input = dataIn.nextInt();
if (input >= 0 && input <= 100) {
grade.add(input);
}else{
System.out.println("invalid input try again..");
}
}while(!(input >= 0 && input <=100));
}
dataIn.close();
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade) {
sum += grades;
}
mean = (double) sum / count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
instead of doing while(checker)
make a loop for while(running)
then send it to the keyboard.nextInt()
if its the wrongAnswer than it will loop, if its correct than set running to false
and have code that follows the while loop

Categories