I have a quick question about the Scanner class.
I had an idea to make a simple program that starts to count all the numbers I write in, but if it goes over a limit it should stop.
This is not the problem....
The problem is that the FIRST number you write in should be the number that tells the program how many numbers it will be counting.
For an example.
When the program starts, I will write in for example :
3
100
234
546
Sum: 880.
and the output should be the sum of 100+234+546.
The number 3 in the beginning just told the program that it is 3 numbers that it should read. I don't understand how to make the first number the number that tells the program how many numbers it should be in the input before it starts to count.
If you are using Java 8, you can do something like this:
Scanner scan = new Scanner(System.in);
int N = scan.nextInt(); //First number is the count of numbers
//line below loops for you and sums at the end
int sum = IntStream.range(0, N).map(i -> scan.nextInt()).sum();
use this code
void yourMethod()
{
int sum=0;
Scanner scan = new Scanner(System.in);
int conut=scan.next();
for(int i=0;i<count;i++)
{
sum=sum+scan.next();
}
}
Store the first number in a variable called counter or similar, and then execute a loop (for, while) for counter times, in each iteration you will read the next number and sum them. The algorithm seems very straightforward to create code from it.
How about:
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
while(count>0){
//your logic
count--;
}
Related
I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}
I'm trying to make an Insertion Sort algorithm in Java, and I want it to read user input, and he/she can put however many numbers they wish (We'll say they're all integers for now, but long run it would be nice to be able to do both integers and doubles/floats), and I want the algorithm to sort them all out. My issue is that when I run this code to see if the integers are adding correctly, my loop never stops.
public class InsertionSort {
public static void main(String[] args){
System.out.println("Enter the numbers to be sorted now: ");
ArrayList<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
while(usrIn.hasNextInt()) {
unsortNums.add(usrIn.nextInt());
System.out.println(unsortNums); //TODO: Doesn't stop here
}
sortNums(unsortNums);
}
}
Now, I suspect it has something to do with how the scanner is doing the .hasNextInt(), but I cannot for the life of me figure out why it isn't stopping. Could this be an IDE specific thing? I'm using Intellij Idea.
Let me know if I left anything out that I need to include.
Your code will stop as long as you stop adding numbers to your input stream. nextInt() is looking for another integer value, and if it can't find one, it'll stop looping.
Give it a try - enter in any sequence of characters that can't be interpreted as an int, and your loop will stop.
As a for-instance, this sequence will cease iteration: 1 2 3 4 5 6 7 8 9 7/. The reason is that 7/ can't be read as an int, so the condition for hasNextInt fails.
When using a scanner on System.in, it just blocks and waits for the user's next input. A common way of handling this is to tell the user that some magic number, e.g., -999, will stop the input loop:
System.out.println("Enter the numbers to be sorted now (-999 to stop): ");
List<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
int i = usrIn.nextInt();
while(i != -999) {
unsortNums.add(i);
i = usrIn.nextInt();
}
I was given an assignment to write a program which will accept any number of input data until 999 has been read. Then the program should type out total number of zero's and various other requests, but the problem is I don't know the output command to tell it to read the number of zeros. All I have so far is
import java.util.Scanner;
public class MidtermI {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
int numbers = console.nextInt();
and then from there I'm lost.
Break it down into small steps, and check that each step works before going further:
The first thing you need to sort out is to be able to read multiple inputs, by looping. Your current code only reads a single number from the Scanner.
Next, you need to check for the special value 999, and stop looping when that is received.
When you have got that working, figure out how to count the zeros - either by counting them as they arrive, or collecting all the values and counting them afterwards.
You can then print out the required results using System.out.println() - but you'll probably want to use that for testing and debugging your code as you go along, anyway.
Create ArrayList to hold the zero values the print its size.
ArrayList<Integer> zeroValues = new ArrayList<Integer>();
Then loop n time to input n numbers:
for(int i=0; i<999; i++) {
int numbers = console.nextInt();
if(number == 0) {
zeroValues.add(number);
}
}
Then you could print the total of zero's values like:
System.out.println(zeroValues.size());
I have the task of writing a program using the fibonacci sequence and putting them into arrays. It works by getting user input ( how many numbers in the sequence the user wants to print out) and then it implements that into an array and prints out the sequence with the number of 'numbers' the user inputed.
As I missed out on 2 weeks of class I looked online on how to write this program and found a video which the following code was written. So I do not take credit for the following code, I'm merely using it as an example.
Anyway here's the code:
public class Fibonacci
{
public static void main(String[] args)
{
int numToPrint;
//how many numbers to print out
Scanner scan = new Scanner(System.in);
System.out.println("Hvað viltu prenta út margar tölur úr Fibonacci röðinni?");
numToPrint = scan.nextInt();
scan.close();
//prints out the first 2 numbers
int nuverandiT = 1;
int lokaT = 0;
System.out.println(lokaT);
System.out.println(nuverandiT);
//prints out the rest of the sequence
int lokaLokaT;
for(int i = 2; i < numToPrint; i++)
{
lokaLokaT = lokaT;
lokaT = nuverandiT;
nuverandiT = lokaLokaT + lokaT;
System.out.println(nuverandiT);
}
}
}
Now this prints out the fibonacci sequence with input from the user, but I'm not quite sure how to make it print out into an array. Do any of you guys know how to do this?
You have to create an array, for example:
int[] simpleArray;
simpleArray = new int[numToPrint];
At the place of
System.out.println(lokaT);
System.out.println(nuverandiT);
Put:
simpleArray[0] = lokaT;
simpleArray[1] = nuverandiT;
And inside your loop, you put instead this:
System.out.println(nuverandiT);
This:
simpleArray[i] = nuverandiT;
I'm guessing when you say 'print out into an array' you really mean you just want to store the values in an array. In that case,
Before your for loop:
int[] array = new int[numToPrint];
And inside your for loop:
array[i-2] = nuverandiT;
If you wanted to print the numbers once they've been stored in an array, you would probably want to loop through it and print in the same fashion, accessing the elements by index. For more information, the java documentation is very good. I recommend reading up on arrays and counted loops.
i am trying to run a very simple java program. i want to write a program that reads 10 integers and that the programs finds witch one is the maximum of them.
i wonder if is possible that inside a loop i can read the 10 values.
Scanner input = new Scanner (System.out);
int num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
System.out.print(" please enter the numer " +i);
===>num[i] = input.nextInt();//
i am trying to find the way to do it without using an array, since i haven't see this in school yet.
any idea how to do it inside a loop? or is just no possible to do?
Sure it's possible.
All you have to do is keep the current maximum value, and then compare it to the value entered by the user for every new value he enters.
You can use the for loop to make sure it runs exactly 10 times.
For that you will have to create int array of 10 length and then read that intvalues in loop and process further.
Example :-
Scanner input = new Scanner (System.out).useDelimiter("\n");
int values[] = new int[10];
.
.
.
for ( int i = 0 ; i < values.length ; i++ ){
System.out.print(" please enter the numer " +i);
values[i] = input.nextInt();
}
If all you need is the maximum value, you don't need to store all ten inputs. So yes, this is possible without an array, and you don't need 10 integer variables either.
(Think about it a bit, you'll see that you can find the maximum in an array by scanning it once. Then you don't need the array anymore.)