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

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 + ".");
}
}

Related

How to store a number of a String-Arraylist to an int variable?

import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and when you are finished enter '=' ");
System.out.print("Enter the first number: ");
ArrayList<String> my_list = new ArrayList<String>();
String value = scanner.next();
int num = Integer.parseInt(value);
if (num == Integer.parseInt(value)) {
my_list.add(value);
} else {
System.out.print("Please enter a number");
}
while (!value.equals("=")) {
System.out.print("Enter a number: ");
value = scanner.next();
my_list.add(value);
my_list.remove("=");
}
System.out.println("The list looks like: ");
System.out.println(my_list);
backarryToNum(my_list);
}
public static void reverseArrayToNum(ArrayList number){
int num;
int sum = 0;
for (int i = number.size()-1; i >= 0 ; i--) {
int n = number.get(i);
num = n * (int)Math.pow(10,i);
sum += num;
System.out.println(sum);
}
}
}
The "int n = number.get(i)" line is the problem.
The method reverseArrayToNum will make the array reverse and will make the reversed array of numbers covert to a number.
Just change
int n = number.get(i);
to
int n = Integer.parseInt((String) number.get(i));
otherwise you try to store a String into an int.
Also, I suppose
backarryToNum(my_list);
is supposed to be
reverseArrayToNum(my_list);

Changing input variables in a java loop

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);
}
}

Im have built a program but I want print out the second input

The program averages out numbers that the users input but I want to take it to another level, I want to print out the second number the user inputed. Do I have to change and reconstruct the program or do I just input something simple?
import java.util.*;
public class InputHere
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
int num;
int counter= 0;
int average;
int total= 0;
System.out.println("Enter 2 Numbers");
while(counter < 2)
{
num= scan.nextInt();
total=total + num;
counter++;
}
average= total/2;
System.out.println("The average is " + average);
}
}
import java.util.*;
public class InputHere {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
int counter = 0;
int average;
int total = 0;
System.out.println("Enter 2 Numbers");
while (counter < 2) {
num = scan.nextInt();
if (counter == 1)
System.out.println(num);
total = total + num;
counter++;
}
average = total / 2;
System.out.println("The average is " + average);
}
}

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

How to sum any amount of user inputted numbers from a single line

Trying to figure out how I would take any amount of inputted numbers from a user and add them together
Example user input: 1 2 3 4
Sum = 10
The user can put any amount of numbers in not a specified amount so if he wanted to add 1 2 3 4 5 6 7 8 9 10 11 12 13, it would sum them all up to 91
Thanks for the help in advance.
import java.util.Scanner;
public class test
{
public static final int SENTINEL = -1;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
while (score >= 0) {
if (score <= -1) {
score = kb.nextInt();
sum += score;
score = 0;
}
System.out.println(sum);
}
}
}
Thanks to libik for all his time and help, here is the finished code.
import java.util.Scanner;
public class JavaApplication1156 {
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
if (sum <= -1)
System.out.println("Application ended");
else if (sum >= 0)
System.out.println("Sum = " + sum);
} while (sum != -1);
}
}
It is very easy actually
import java.util.Scanner;
public class JavaApplication115 {
public static void main(String[] args) {
System.out.println("write numbers, if you write zero, program ends");
Scanner input = new Scanner(System.in); //just copy-and paste this line, you dont have to understand it yet.
int number;
int sum = 0;
do {
number = input.nextInt(); //this reads number from input and store its value in variable number
sum+= number; //here you add number to the total sum
} while(number != 0); //just repeat cycle as long as number is not zero
System.out.println("Sum is : " + sum);
}
}
Working code based on your code :
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println(sum);
}
Also if you are interested in "minimal" version, which is the same as the one before, but using as less code as possible, here it is :
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter numbers here");
Scanner kb = new Scanner((new Scanner(System.in)).nextLine()); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
sum += kb.nextInt();
}
System.out.println(sum);
}
Find sum of each line as long as sum is not zero (based on second block of code) :
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println("Sum = " + sum);
} while (sum != 0);
}
//Input the number in a single line (but be in size limit of integer)
import java.util.Scanner;
public class Sum_of_integers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
while(num >= 1) { //base value
int lastval = num % 10; //the logic
num = num / 10;
sum += lastval;
}
System.out.println(sum);
}
}
Question - Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all.
Scanner sc = new Scanner(System.in);
int input = 0;
int sum = 0;
while (true){
sum = sum+input;
if (input==5){
System.out.println("Loop is stopped");
System.out.println("The sum is " + sum);
break;
}
else {
System.out.println("Take the inputs");
input = sc.nextInt();
}
}

Categories