I have declared a Scanner object named Scan
I want to prompt the user to enter however many items they like:
ie: Enter items: 1 2 6 4 3 12
how do I count how many numbers were entered? For example, the output from above should be 6, since there are 6 numbers
I have tried
int count = 0;
while(Scan.hasNextInt()){
count++ };
You can split the line on whitespace and get the number of parts.
final String line = Scan.nextLine();
if(line.trim().isEmpty()){
System.out.println("Nothing entered");
} else {
final String[] parts = line.split("\\s+");
System.out.println(parts.length);
}
Demo: https://ideone.com/zgr6zM
To convert the parts to an int array, you can use Arrays.stream and .mapToInt.
final int[] nums = Arrays.stream(parts).mapToInt(Integer::parseInt).toArray();
Demo: https://ideone.com/WevrTw
You need to actually call scanner.nextInt() or your scanner's "pointer" will never move past the first number.
jshell> while(scanner.hasNextInt()) {
...> count++;
...> scanner.nextInt();
...> }
1 2 3 4 5 6
jshell> count
count ==> 6
You can read in numbers as follows.
2 3 12 3 1 2
2 29 122 q
The main point is that hasNextInt will continue reading from the console until a non-integer is entered.
Scanner scan = new Scanner(System.in);
List<Integer> numbs = new ArrayList<>();
System.out.println("Enter ints followed by any letter to quit");
while (scan.hasNextInt()) {
numbs.add(scan.nextInt());
}
System.out.println("The following " + numbs.size() + " numbers were entered.");
System.out.println(numbs);
The above sample input would print.
The following 9 numbers were entered.
[2, 3, 12, 3, 1, 2, 2, 29, 122]
Related
Hi i want to learn how to do java loop that will determined the number if it is an odd or even like
1st value: 8
2nd value: 15
output:
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
You can do it like so:
Scanner input = new Scanner(System.in);
System.out.print("First value: ");
int start = Integer.parseInt(input.nextLine());//Gets the first number
System.out.print("Second value: ");
int end = Integer.parseInt(input.nextLine());//Gets the second number
for(int i = start; i <= end; i++){
if(i%2==0){//When the number is divided by 2, it gives a remainder of 0. Modulus helps us get the remainder.
System.out.println(i+" is even");
}else{//Doesn't satisfy the first condition. It must be odd.
System.out.println(i+" is odd");
}
}
We use a Scanner to read the user input, then use a for loop and leverage modulus (%). Modulus calculates the remainder of a number after dividing it by a certain number. If a number divided by 2 gives a remainder of 0, that means it is divisible by 2. We can construct an if statement to check whether it is divisble.
Test Run
First value: 1
Second value: 10
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Hey you can use a for loop it's simple.
for(int i=8;i<=15;i++){
if(i%2==0){
System.out.println(i+"is even");
}else{
System.out.println(i+"is odd");
}
}
And I expect you know how to ask inputs so just pass it on the place of 8 and 15
The short version:
https://www.youtube.com/watch?v=cakN0XC6CcQ
Use number % 2 == 0 for even numbers.
The long version:
// Create a new Scanner() to scan System.in
Scanner scanner = new Scanner(System.in);
// Get the two inputs
int first = scanner.nextInt();
int second = scanner.nextInt();
// Start i as the first number
// While it is less than or equal to the second
// Add one each time
for(int i = first; i <= second; i++) {
// Is there a remainder from dividing i by 2?
// If no, it's even
boolean even = i % 2 == 0;
// Print it
System.out.println(i + " is even: " + even);
}
scanner.close();
I am looking for a way to add elements into two different arrays, changing between the arrays.
For example:
Input: 1
Input: 2
Input: 3
Input: 4
Input: 5
Input: 6
Array1 = [1, 3, 5]
Array2 = [2, 4, 6]
Any help/code would be appreciated.
You can try the following code:
Scanner input=new Scanner(System.in);
int[] ar1=new int[3];
int[] ar2=new int[3];
int evenIndex=0;
int oddIndex=0;
for(int i=0;i<ar1.length+ar2.length;i++){
System.out.println("Enter number");
int num=input.nextInt();
if(i%2==0)// if the index is even number
{
ar1[evenIndex]=num;
evenIndex++;
}
else{
ar2[oddIndex]=num;
oddIndex++;
}
}
for(int i=0;i<ar1.length;i++)//print the result of array1
System.out.print(ar1[i]+" ");
System.out.println();
for(int i=0;i<ar2.length;i++)//print the result of array2
System.out.print(ar2[i]+" ");
Example:
Enter number
1
Enter number
2
Enter number
3
Enter number
4
Enter number
5
Enter number
6
1 3 5
2 4 6
Simple: you created TWO arrays of size N.
But when you intend to put N/2 elements into the first array, and N/2 elements into the other, then both your arrays should have length N/2.
In other words: your arrays of length N are preset with 0 values. You put values into every second slot, and the others stay 0.
I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.
The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.
Input and Output example on Command line:
$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1
I've tried to convert the Integers to an array
int[] n = StdIn.readAllInts();
but it doesn't work when tried to print it out.
can anybody give me some tips?
You should be able to catch it as a string with a normal scanner:
Scanner in = new Scanner(System.in);
String line = in.nextLine();
sometimes the second line don't work for some inputs, so you can also try:
String line = in.next();
to get the numbers as integers you can use inputStream, but I'm not sure how will work.
A possible solution could be:
int testNum;
Set<Integer> set = new HashSet<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("number of elements to be inserted");
testNum = in.nextInt();
//Add items
for ( int i = 0; i<testNum; i++)
{
set.add(in.nextInt());
}
//Print all element
Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
I hope to have helped you
Sample program below, this removes the duplicate entries but still retains the order.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5 ");
String input = sc.nextLine();
String[] numbers = input.split("\\s+");
List<String> result = new ArrayList<>();
for (int x = 0; x < numbers.length; x++) {
String item = numbers[x];
if (result.contains(item)) continue;
result.add(item);
}
System.out.println(String.join(" ", result));
}
And output sample is:
Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5
1 1 2 2 1 1 1 3 4 1 1 1 11 11 12 12 1 1 6 6 2 1 //sequence entered
1 2 3 4 11 12 6 // sample result
Stdin is not needed.
By calling
java RemoveDuplicates 1 1 2 2 1 1 3 4 6 2 1
It assigns String[] args to an array of all those values.
If you want to remove duplicates, put them in a Set
public static void main(String[] args) {
Set<String> uniq = new HashSet<>();
for (String s : args) {
uniq.add(s);
}
System.out.println(uniq);
}
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should: output the individual digits of 3456 as 3 4 5 6 and the sum as 18, output the individual digits of 8030 as 8 0 3 0 and the sum as 11, output the individual digits of 2345526 as 2 3 4 5 5 2 6 and the sum as 27, and output the individual digits of 4000 as 4 0 0 0 and the sum as 4.
Moreover, the computer always adds the digits in the positive direction even if the user enters a negative number. For example, output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the question I'm having minor difficulties with, the only part I can't figure out is how can I print the single integers in the order that he wants, from what I learned so far I can only print them in reverse. Here's my code:
import java.util.*;
public class assignment2Q1ForLoop {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
int usernum, remainder;
int counter, sum=0, N;
//Asaking the user to enter a limit so we can use a counter controlled loop
System.out.println("Please enter the number of digits of the integer");
N = console.nextInt();
System.out.println("Please enter your "+N+" digit number");
usernum = console.nextInt();
System.out.println("The individual numbers are:");
for(counter=0; counter < N; counter++) {
if(usernum<0)
usernum=-usernum;
remainder = usernum%10 ;
System.out.print(remainder+" ");
sum = sum+remainder ;
usernum = usernum/10;
}
System.out.println();
System.out.println("the sum of the individual digits is:"+sum);
}
}
You have to storeremainder variables in an array and then print them in the loop from last index to first as shown in this tutorial.
You can either store digits in array and then print them, or you can try something like that:
final Scanner console = new Scanner(System.in);
System.out.println("Please enter your number");
final int un = console.nextInt();
long n = un > 0 ? un : -un;
long d = 1;
while (n > d) d *= 10;
long s = 0;
System.out.println("The individual numbers are:");
while (d > 1) {
d /= 10;
final long t = n / d;
s += t;
System.out.print(t + " ");
n %= d;
}
System.out.println();
System.out.println("the sum of the individual digits is:" + s);
An idea would be : convert int to string and write a method
getChar(int index) : String
which gives you for example 4 from 3456 with
getChar(2);
See Java - Convert integer to string
Here, I wrote a code for your problem with using a stack. If you want a simple code, you can comment my solution and I will wrote another one.
Scanner c1 = new Scanner(System.in);
System.out.print("Enter the number: ");
int numb = c1.nextInt();
numb = Math.abs(numb);
Stack<Integer> digits = new Stack<Integer>();
while(numb>0){
int n = numb%10;
digits.push(n);
numb = numb/10;
}
int sum = 0;
while(!digits.isEmpty()){
int n = digits.pop();
sum+=n;
System.out.print(n+" ");
}
System.out.print(sum);
public void main()
{
System.out.println();
Scanner input = new Scanner(System.in);
ArrayList<Integer>nums1 = new ArrayList<Integer>();
ArrayList<Integer>nums2 = new ArrayList<Integer>();
ArrayList<Integer>numsFinal = new ArrayList<Integer>();
System.out.println("Merger.");
System.out.println("Enter number of times to merge: ");
int n = input.nextInt();
int o = 0, p = 0;
for(int i=0;i<n;i++){
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("Enter the first list of descending positive values followed by any letter when finished: (ex. 1 2 3 4 5 y)");
while(input1.hasNextInt()){
nums1.add(input1.nextInt());
}
System.out.println("Enter the second list of descending positive values followed by any letter when finished: (ex. 6 7 8 9 10 p)");
while(input2.hasNextInt()){
nums2.add(input2.nextInt());
}
while(nums1.get(o)<nums2.get(o)||nums1.get(o)==nums2.get(p)){
numsFinal.add(nums1.get(o));
o++;
while(nums2.get(p)<nums1.get(o)||nums2.get(p)==nums1.get(o)){
numsFinal.add(nums2.get(p));
p++;
}
}
System.out.println(numsFinal);
}
}
This is what I have so far, but I can seem to grasp the area where you traverse through both arraylists. Help Appreciated! I finished the part where the user's inputted values are stored into two separate arrays. The merging into a third array is what is troublesome.
Ex input: 1 2 3 4 5
end of first input
5 7 9 11 13
end of second input
output: 1 2 3 4 5 7 9 11 13