I cant figure out how to add the values after it spits out the numbers.
it says:
Number: 5 // I typed 5
1 2 3 4 5
The sum is.
So i need to add those number 1 2 3 4 5 but cant figure out how.
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run=run+1)
{
System.out.print( run + " " );
sum = sum + 1 ;
}
System.out.println( "The sum is . " );
}
}
You need to add run to sum and then print it out, like this:
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run=run+1)
{
System.out.print( run + " " );
sum = sum + run;
}
System.out.println( "The sum is " + sum );
}
}
System.out.println( "The sum is: " + sum );
the + sum seems weird but you can use it the and a number value to a string
import java.util.Scanner;
public class AddLoop {
public static void main(String[] args) {
int sum = 0;
for(int i=1 ; i<=10 ; i++){
Scanner s = new Scanner( System.in);
System.out.println("Enter number" + " " + i);
int b = s.nextInt();
sum = sum + b;
}
System.out.println("The result is :" + sum );
}
}
I believe you want sum = sum + run;
if you are wanting to sum (1, 2, 3, 4, 5) = 15.
Fahd's answer is pretty much what you're looking for (he posted while I was typing mine). My answer just has a little bit different syntax to perform the loop and sum.
import java.util.Scanner
public class AddingValuesWithAForLoop { public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( " \n" );
System.out.println( "Number: " );
int number = keyboard.nextInt();
int sum = 0;
for (int run=1; run<=number; run++)
{
System.out.print( run + " " );
sum += run;
}
System.out.println( "The sum is " + sum + "." );
}
}
well the way your doing it you will need to do keyboard.nextLine(); that will set all of your numbers to a string. Once you have all of your numbers in string you can parse through the string and set that as the scanner then do nextInt()
import java.util.Scanner
public class AddingValuesWithAForLoop
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Number: ");
string numbers = keyboard.nextLine(); // 5 1 2 3 5
Scanner theNumber = new Scanner(numbers);
int sum = 0;
for (int run = theNumber.nextInt(); run > 0; run--)
{
System.out.print(run + " ");
sum += theNumber.nextInt();
}
System.out.println("The sum is: " + sum);
}
}
Here is the code that might be helpful:
import java.util.Scanner;
public class AddLoop {
public static void main(String[] args) {
int sum = 0;
for(int i=1 ; i<=10 ; i++){
Scanner s = new Scanner( System.in);
System.out.println("Enter number" + " " + i);
int b = s.nextInt();
sum = sum + b;
}
System.out.println("The result is :" + sum );
}
}
Hope this answer help you.
Assume that input value is 6, So internally add all the consecutive numbers until 6. I.e Since the input value is 6, output should be like this
0+1+2+3+4+5=15
Refer to the below snippet
public void testAdding() {
int inputVal = 6;
String input = "";
int adder = 0;
for(int i=0; i < inputVal; i++) {
input = String.valueOf(i);
if(inputVal == (i+1)) {
System.out.print(input);
} else {
System.out.print(input+"+");
}
adder =+ i + adder;
}
System.out.print("="+adder);
}
Related
I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}
I started to study JAVA, So sorry for the question.. I practice the WHILE LOOP, so I have this code:
import java.util.Scanner;
public class Class {
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
double n = 0;
while ( n < 10 )
{
System.out.println( (n+1) + "." + message );
n++;
}
}
}
so, I want to get a result somthing like that: 10. 20. 30. and etc..
but I get: 1.0. , 2.0., 3.0. and etc..
what I should do to remove this dot, between 1 and 0...? thank you very much for your help :).
Use int instead of double for n variable:
int n = 0;
Well, a quick fix to your problem would be first changing the data type to int, so int n = 0; then simply add "0." to your print statement, so it looks like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 0;
while ( n < 10 ) {
System.out.println( (n+1) + "0." + message );
n++;
}
}
}
Or, alternatively, you could do int n = 10 and have your while loop condition aswhile( n < 100 ) then increment n by ten (n+=10;). So now it would look like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 10;
while ( n < 100 ) {
System.out.println(n + "." + message);
n+=10;
}
}
}
you can increment in 10s by multiplying n by 10, Also you might want to use int type rather than double to remove the decimal point.
int n = 1;
while ( n <= 10 )
{
System.out.println( ( 10 * n) "." + message );
n++;
}
You can try something like this:
int n = 10; // start from 10 and change it from double to int to get rid of decimal point
while ( n <= 100 ){
System.out.println( n + "." + "message");
n+=10; // increment by 10 after every loop
}
I am trying to make a for loop to print out all of the following strings to go into the println statement below but cannot figure out how to get the for loop to print the Array. I keep getting the error 'cannot find symbol.' There will be a scanner that allows for user inputs after each println statement.
public static void Real() {
String[] sequence;
sequence = new String[4];
sequence[0] = ("first");
sequence[1] = ("second");
sequence[2] = ("third");
sequence[3] = ("fourth");
int number;
for (number = 0; number <= sequence(); number++ ) {
System.out.println("Input your " + sequence + " lap time");
}
}
A couple of syntax errors present in your code, also, method name in java should start with a lowerase.
Code below should do the work.
public static void real() {
String[] sequence;
sequence = new String[4];
sequence[0] = "first";
sequence[1] = "second";
sequence[2] = "third";
sequence[3] = "fourth";
int number;
for (number = 0; number < sequence.length; number++ ) {
System.out.println("Input your " + sequence[number] + " lap time");
}
}
use number<sequence.length instead of number <= sequence()
and
use sequence[number] instead of sequence inside system.out.println()
public static void Real(String a[]) {
String[] sequence;
sequence = new String[4];
Scanner input= new Scanner(System.in);
sequence[0] = ("first");
sequence[1] = ("second");
sequence[2] = ("third");
sequence[3] = ("fourth");
int number;
for (number = 0; number <4 ; number++ ) {
System.out.println("Input your " + sequence[number] + " lap time");
System.out.println("Input");
variable = inupt.nextDatatype();
}
}
this is the answer after what i understood.
i don't know about this by the way sequence();
You can't print an array just by referring to its name in a print statement, you need to loop through all the elements and print element at each index. You access an element using the syntax array[index].
You need to loop from 0 to the last index, I think what you're trying to get from sequence() is the size of the array. To get the size of array you need to use array.length
So your code should look like this :
public static void Real() {
String[] sequence;
sequence = new String[4];
sequence[0] = ("first");
sequence[1] = ("second");
sequence[2] = ("third");
sequence[3] = ("fourth");
int number;
for (number = 0; number < sequence.length; number++) {
System.out.println("Input your " + sequence[number] + " lap time"); } }
How about using for-each loop?
for (String s : sequence)
System.out.println("Input your " + s + " lap time");
I am new to java programming. I am trying to convert an string variable with array to an int variable array
but i have 2 errors and have no idea to fix it,
any help would be great, thanks..
This is my source code :
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int sum=0;
for(x=0;x<=1;x++)
{
System.out.print("input number : ");number[x]=in.next();
int value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum+number[x];
}
for(x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
This is what the errors look like
when you convert an array of stirngs to an array of integers,
we should have an array of integers declared
and in the code that you posted there are some syntax errors because you didnt declare integer array before use(int value[x])
and try the below code which will convert string array of numbers(string number[]) into an ineger array of numbers(int value[])
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100]; // here I declared an array of integers with the name value
int sum=0;
for(int x= 0;x <= 1; x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum + value[x];
}
for(int x=0; x<=1; x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
Use in.nextInt() method.
Scanner in = new Scanner(System.in);
int number[] = new int[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {`enter code here`
System.out.print("input number : ");
number[x] = in.nextInt();
sum = sum + number[x];
}
System.out.println("Sum :\t " + sum);
in.close();
}
Create a int array, then use it. int value[x]= Integer.parseInt(number[x]); is an error because your are trying to assign an integer to an array.
Correct one may be...
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100];
int sum=0;
for(int x=0;x<=1;x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]);
sum=sum+value[x];
}
for(int x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
There seems problem with declaration and usage of variable in you sample code.
Variable x is not initialzed
An integer value is assigned to and array declaration.
Try the below code to solve your issues.
import java.util.Scanner;
public class stringtoint {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {
System.out.print("input number : ");
number[x] = in.next();
int value = Integer.parseInt(number[x]);
sum = sum + value;
}
for (int x = 0; x <= 1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
in.close();
}
}
public static void main(String args[]) {
String[] exampleOfStringArray = {"11", "22", "33"/*, "ab", "cd", "ef", "", null*/};
int[] intArray = getIntArray(exampleOfStringArray);
int sum = getSumOf(exampleOfStringArray);
}
private static int[] getIntArray(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).toArray();
}
private static int getSumOf(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).sum();
}
Try below code, it is working.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
int noOfInputs = 2;
int value[] = new int[noOfInputs];
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.print("input number : ");
number[x] = in.next();
value[x] = Integer.parseInt(number[x]);
sum = sum + value[x];
}
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
}
I wrote a small program consisting of two classes. I am trying to call the methods from the second class but I get an error.
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: The method getSum(int[]) is undefined for the type
UserInteraction The method getAverage(int[]) is undefined for the type
UserInteraction at UserInteraction.main(UserInteraction.java:66)
Here's the code of the first class:
import java.util.Scanner;
public class UserInteraction {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice = 0;
String[] subjects = new String[10];
int grades[] = new int[10];
double sum = 0.0;
Grades method = new Grades();
do
{
System.out.println("1. Enter a course name and a grade");
System.out.println("2. Display all grades");
System.out.println("3. Calculate the average grade");
System.out.println("4. Exit program");
choice = scan.nextInt();
if ( choice == 1 )
{
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Enter 10 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 10; i++ )
{
System.out.println("Subject:");
String temp = scansubjects.nextLine();
subjects[i] = temp.toLowerCase();
System.out.println("Grade:");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length - 1 ) )
{
System.out.println("Thank you!");
System.out.println();
}
}
}
if ( choice == 2 )
{
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for(int p = 0; p < subjects.length; p++)
{
System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
}
}
if ( choice == 3 )
{
System.out.println("Total of grades: " + getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + getAverage(grades));
System.out.println();
}
} while ( choice != 4);
}
}
And the second class is:
public class Grades {
public static double getAverage(int[] array)
{
int sum = 0;
for(int i : array) sum += i;
return ( ( double ) sum )/array.length;
}
public static double getSum(int[] array)
{
int sum = 0;
for (int i : array)
{
sum += i;
}
return sum;
}
}
You don't need this, because it only has static methods:
Grades method = new Grades(); // <-- delete this line
To call static methods they must be preceded with their class name like this:
System.out.println("Total of grades: " + Grades.getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + Grades.getAverage(grades));
Your code doesn't compile. Don't try to execute non-compiling code. Fix all the compilation errors before executing the code. They're visible in the "Problems" view of your Eclipse IDE.
You need to call Grades.getSum and Grades.getAverage to get the right result. Also, don't forget to import the Grade class, using the command import Grades; in the beginning of the UserInteraction class.