Using while loops to print out vaules [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently doing a college lab on while loops and I'm stuck and would appreciate any help available. I have to write a program as follows
Write a program MaxNum that reads in a sequence of 10 positive integers, and
outputs the maximum of the sequence
Now I could just make 10 ints and make the user input a value but I'm not sure how to do that with a while loop?
Here is the code I have at the moment :
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
System.out.println("Please enter 10 integers");
do
{
for(Num1 = 0; Num1 < 10; Num1++);
{
Num1 = in.nextInt();
}
}
while(Num1 > 0);
}
}

Since you can't use array, you just use a max to check if the number entered is bigger than the previous number entered. You don't need a while loop, at least your do-while is not really needed in this case.
Edit: don't modify num1, you will be messing around with your for-loop
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
int max = 0;
int userInput = 0;
System.out.println("Please enter 10 integers");
for(Num1 = 0; Num1 < 10; Num1++);
{
userInput = in.nextInt();
if(num1 == 0){//you set your first number as the maximum
max = userInput;
}else if(max < userInput){
max = userInput;//here you set the number to max
}
}
}
}

Here is something you could do since you explicitly saying you are learning the while loop. You can keep getting user's input until you have enough number of Integers entered, since you mentioned you only want Integer. And you can use Collections.max at the end.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (list.size() < 10 && scanner.hasNext()) {
if (scanner.hasNextInt()) {
list.add(scanner.nextInt());
} else {
scanner.next();
}
}
Integer max = Collections.max(list);
System.out.println(max);
}

Related

I am trying to use the scanner inputs for a for loop that counts the number from the min to max and display the numbers in the terminal [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to count a range of number with a for loop using input from scanner.
Tried writing the code but still no results
package com.example.myapplication;
import java.util.Scanner;
public class dsd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number:");
int firstnum = sc.nextInt();
System.out.println("Enter first number:");
int secondnum = sc.nextInt();
System.out.print("counting ");
for (int i = firstnum; i >= secondnum; i++) ;
{
System.out.print(i);
}
}
Upper limit :5
Lower Limit :2
Expected to see COunting 2 ,3 ,4, 5
I think it would be better to use a camel case to match the coding convention. And if you put a semicolon after the for loop, the following code will not be executed. Of course, the conditional statements in the for loop seem a little wrong.
For the example given in the question, see the code below:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Upper limit:");
int firstNum = sc.nextInt();
System.out.print("Lower Limit:");
int secondNum = sc.nextInt();
System.out.print("counting ");
for (int i = secondNum; i <= firstNum; i++) {
System.out.print(i);
}
}
Result (in the terminal)
Upper limit:5
Lower Limit:2
counting 2345
I have seen this mistake many times:
for (int i = firstnum; i >= secondnum; i++) ;
Please remove the ;
Is the first number always greater than the second?
If so, you should write it as the code below.
// Delete semicolon. and less then change
for (int i = firstnum; i <= secondnum; i++) {
System.out.print(i);
}
In your code you have used the "sc" scanner for both firstnum/secondnum variable. The loop of your code will print only the last number inserted.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i;
int start, end;
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
/*
* The block try-catch highlights the fact that you cannot insert min
* number bigger than the max number
*/
try {
System.out.print("Enter first number:");
start = sc.nextInt();
System.out.print("\nEnter second number: ");
end = sc1.nextInt();
if(start > end) throw new Exception();
i = start;
while (i<=end){
System.out.println("count: " + i);
i++;
}
}catch(Exception e){
System.out.println("You cannot start with number bigger than 'end-number' ");
}
}
}

Sum of Digits of the Input from user [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a code that will get the sum of all the digits of the input,
sample input: 241 sample output: 7
But there are restrictions in in making the program, only the basic operations, functions should be used and no string function is to be used in getting the said sum of the digits only (loop, /, %, *,-,+)are allowed to be used.
The program I am thinking should start with this..
public class SumOfDigits{
public static void main(String args[]) throws Exception{
Scanner input = new Scanner(System.in);
int num = input.nextInt();
while(){
}
}
}
One option would be to use a modulus trick to isolate, and then sum, each digit in the input number:
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
Follow the link below for a working demo.
Demo
modulu 10 of the number will give you the last digit, the dividing it by 10 will give you the other digits, due to integer division. You can loop until you've handled all the digits:
int sum = 0;
while (num != 0) {
sum += (num % 10);
num /= 10;
}
you can use a recursive function like this
import java.util.Scanner;
public class Main {
Scanner scanner ;
int result = 0;
public static void main(String[] args) {
// initialize new instance of current class
Main thisIns = new Main();
// initialize scanner instance for this instance
thisIns.scanner = new Scanner(System.in);
//calling for getting user inputs
int i = thisIns.getUserInput();
//get the sum of the integer
thisIns.getSumOfInterger(i, 0);
System.out.println("result is " + thisIns.result);
}
public int getUserInput(){
System.out.println("Please enter an integer : ");
int i = scanner.nextInt();
return i;
}
public void getSumOfInterger(int i, int moduler) {
if (i != 0) {
moduler += i%10;
getSumOfInterger(i/10, moduler);
// return 0;
}else{
result = moduler;
}
}
}

How to use a loop where integers are inputted?

I'm working on a question and I'm new to programming, so I'm not that familiar with a few concepts. The question asks the user to input an initial number, followed by a list of that many numbers. The program should then print back how many of the numbers entered were negative.
For example, I first input 5, followed by 5 other random numbers.
5
6,-9,28,-32,-1
The output should be
3
So far all I have is:
class main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++)
{
System.out.println(i);
if(i<0)
{
c++;
}
}
System.out.println(c);
}
}
I'm really confused. Can someone offer an explanation as to how the code works?
You can read the positive integers inside for loop from the given inputs and then check if that each input integer is greater than or equal to zero:
scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++) {
int num = scan.nextInt();
if(num>=0)
{
System.out.println(num);
}
}

How to calculate an factorial with loops in java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to write a portion of a program that calculates factorials using loops. I don't have any error messages, but I'm not getting any output.
Are there suggestions for my approach or is there a better approach using loops? Thanks!
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
//Execute factorial
do{
factTotal = factTotal * number;
number--;
while (number >= 1);
}
while (number <= 0);{
System.out.println("That's not a positive integer!");
}
System.out.print(factTotal);
}
}
This is the way I would approach the factorial portion of your problem. I would do away with the do/while loops because it appears that you are getting stuck in an infinite loop if you aren't getting output.
//Call this method when you want to calculate the factorial
public int factorial(int num){
for(int i = num-1; i > 1; i--){
num *= i;
}
return num;
}
This is what it would look like in your code.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
if(number > 0){
factTotal = factorial(number);
System.out.print(factTotal);
}
else
System.out.println("This is a negative number");
}
#Pernicious, Please see your program with slight modifications and my comments added. I think this is what you were trying to do.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
// The input number check should be before factorial calculation
if(number <= 0){
System.out.println("That's not a positive integer!");
System.exit(0);
}
//Execute factorial
do {
factTotal = factTotal * number;
number--;
// while (number >= 1); This while should be after do{}, not within do{}
} while (number >= 1);
// This check should be done immeduately after user input, not after calculation of factorial.
// while (number <= 0);
// {
// System.out.println("That's not a positive integer!");
// }
System.out.println(factTotal);
}
}
In your code, in the do...while loop, you have used this while statement:
while (number >= 1);
Did you not notice the semicolon? And what is the point of this loop? Currently it is leading to an infinite loop as the value of number never changes and thus you are getting no output. Also, your second while loop should much rather be an if statement as shown below
That piece of code is equivalent to:
while (number >= 1)
{
//doNothing
}
I believe you meant to do:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
//Create scanner object for reading user input
Scanner input = new Scanner(System.in);
//Declare variables
int number = input.nextInt();
int factTotal = 1;
//Execute factorial
do{
factTotal = factTotal * number;
number--;
}
while (number <= 1);
if(number < 0)
{
System.out.println("That is not a positive integer");
}
else
System.out.print(factTotal);
}

Arrays with user input

I am trying to write a program that repeatedly asks the user to supply scores (out of 10) on a test.It needs to continue until a negative value is supplied. Values higher than 10 should be ignored. I also calculated the average of the inputs. After the scores have been inputted, i need to use a single array to produce a table that automatically fills the test scores and the number of occurrences of the certain test score.
I wanted it to look something like this:
Score | # of Occurrences
0 3
1 2
2 4
3 5
4 6
and so on.. P
I am a beginner and this is my first question, so i am sorry if i made a mistake in posting the question or something.
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main()
{
Scanner kbReader= new Scanner (System.in);
int score[] = new int [10];//idk what im doing with these two arrays
int numofOcc []= new int [10];
int counter=0;
int sum=0;
for (int i=0;i<10;i++)// Instead of i<10... how would i make it so that it continues until a negative value is entered.
{
System.out.println("Enter score out of 10");
int input=kbReader.nextInt();
if (input>10)
{
System.out.println("Score must be out of 10");
}
else if (input<0)
{
System.out.println("Score must be out of 10");
break;
}
else
{
counter++;
sum+=input;
}
}
System.out.println("The mean score is " +(sum/counter));
}
}
You could use a do...while loop like this:
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main(String args[]) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [10];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 10 or negative to break.");
input=kbReader.nextInt();
if (input<0) {
break;
} else if (input>10) {
System.out.println("Score must be out of 10");
} else {
scores[input]++;
counter++;
sum+=input;
}
} while (input>0);
System.out.println("Score\t# of occur...");
for(int i =0; i<10; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}
The formatting can certainly be done better (without c-style tabs) but I don't remember the syntax at the moment.
I think what you need is a List Array! Create ArrayList from array
Think of it as a dynamic array, you don't need to specify the size of the array and it is expanded/made smaller automatically.
What you're missing is a while loop. Here is a nice way to loop through a Scanner for input. It also catches numbers greater than 10 and provides an error message:
public static void main() {
Scanner s = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int response = 0;
while (response >= 0) {
System.out.print("Enter score out of 10: ");
response = s.nextInt();
if (response > 10) {
System.out.println("Score must be out of 10.");
} else if (response >= 0) {
list.add(response);
}
}
// Do something with list
}

Categories

Resources