How can i input multiple times in one line? [duplicate] - java

This question already has answers here:
How to read multiple Integer values from a single line of input in Java?
(21 answers)
Closed 1 year ago.
How can I input multiple times in one line?
public class Awit {
static void numbers(){
Scanner user = new Scanner(System.in);
int arraylist[] = new int [5];
System.out.println("Enter five integers:");
System.out.print("");
for(int i = 0; i<=4; i++){
arraylist[i] = user.nextInt();
}
public static void main (String []args){
numbers();
}
}
Output:
Enter five integers:
1
2
3
4
5
I want the output to be like this
1 2 3 4 5

The program that you have written will read multiple numbers from a line ... if you give it multiple numbers on a line.
$ java Awit.java
Enter five integers:
1 2 3 4 5
$
The only issues with the code you have written are:
it is missing an import for Scanner, and
there is a } missing at the end of your numbers method.
Those problems will give compilation errors. Assuming that you correct them, you will not get any output (apart from the prompt to enter some numbers) because your program doesn't print the array(!)
If you want to know how to print the numbers, read the following:
What's the simplest way to print a Java array?

Related

Why is was my code not performing with negative values inputted? [duplicate]

This question already has answers here:
Mod in Java produces negative numbers [duplicate]
(5 answers)
Closed 3 years ago.
Sorry im just learning java and im new to coding!
The task of my code is to evaluate input in terms of odd and even numbers.
Without the math.abs line the code would not recognize the odd/even values of negative numbers correctly.
i made a fix using the math.abs command to convert the negative value and get the desired result. But, i just wanted to know why this step is necessary and how java scanner interprets the negative value/symbol and provides the wrong answer without my fix.
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type a number: ");
int x = Integer.parseInt(reader.nextLine());
int f = Math.abs(x);
if ( f % 2 == 1){
System.out.println("The number is odd.");
}
else {
System.out.println("The number is even.");
}
}
}
The remainder of a negative number divided by a positive number will be negative.
-1 % 2
is
-1
but since that is not 1, you will declare it to be even.

Number to Binary to Zero Counter [duplicate]

This question already has answers here:
How to format a Java string with leading zero? [duplicate]
(24 answers)
Closed 5 years ago.
So my program is meant to take user input which is supposed to be a number from 1-511. Once the number is entered my program uses Integer.toBinaryString(); to turn their number into the binary form of that number. Then, if the binary output is not 9 digits, I want to fill the rest of that binary number with 0's until its 9 digits long. So I use an if statement to check if the length of the binary is less than 9, if it is I have it set to subtract 9 from binary.length so we can know how many zeros we need to add. Im currently stuck so I just made a print statement to see if its working so far and it does. But im not sure what to do as far as finishing it.
import java.util.Scanner;
public class Problem8_11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter one number between 0 and 511: ");
int number = input.nextInt();
int binaryZeros = 9;
String binary = Integer.toBinaryString(number);
if(binary.length() < 9) {
int amountOfZeros = 9 - binary.length();
System.out.print(amountOfZeros);
}
}
My question: How do I add the zeros to binary?
Presumably you want to prepend the zeros. There are many ways to do this.
One way:
StringBuffer sb = new StringBuffer( Integer.toBinaryString(number) );
for ( int i=sb.length(); i < 9; i++ ) {
sb.insert( 0, '0' );
}
String answer = sb.toString();
Be sure to handle the case where the number cannot be parsed into an integer.

why the exception is thrown when it should not [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I'm creating a program of letting people enter 10 integers and display them from the smallest to the largest. Here is my program:
import java.util.Scanner;
public class EnterTenNumbers {
public static void main(String[] args){
System.out.println("Enter 10 numbers");
int small=0;
for(int i=0; i<10; i++){
Scanner in=new Scanner(System.in);
int[] i1=new int[10];
int num=in.nextInt();
i1[i]=num;
if(i1[i]<i1[i+1] || i1[i]==i1[i+1]){
System.out.println(i1);
}else if(i1[i]>i1[i+1]){
i1[i+1]=i1[i];
System.out.println(i1);
}
}
}
}
When I run my program, after the user input the numbers, such things like "[I#55f96302" appear.
And after the user entered 10 integers, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at EnterTenNumbers.main(EnterTenNumbers.java:13)
appears while it should display the numbers from smallest to largest.
What happened?
Every time you are asking the user to give a number as input, you are creating a new array of integers. Aren't you supposed to create only one array to hold those 10 integers ? So, declare the integer array outside the loop. in this way, it will be declared only once.
You have to take all the 10 integers from user at the very beginning, then you have to run the operations over these 10 integers in order to show them from smallest to the largest.
after taking all the 10 integers from user and saving them in An array, you have to again loop through among those numbers one by one and check which number is smallest and which number is largest. When the loop check the last index of the array, you can't check the next index of that array (because that index of the array doesn't exists). That's why you are having an exception every time.
if(i1[i]<i1[i+1] || i1[i]==i1[i+1]){
System.out.println(i1);
}else if(i1[i]>i1[i+1]){
i1[i+1]=i1[i];
System.out.println(i1);
}
When I run my program, after the user input the numbers, such things
like "[I#55f96302" appear.
This is because you are printing the string representation of your array, not the elements of the array.
Replace
System.out.println(i1);
with
System.out.println(i1[i]);
And after the user entered 10 integers, Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 10
As the exception clearly indicates, you are trying to access 10th index (index starts from 0) or 11th element of the array. But your array has only 10 elements. So that's why you get AIOOBE. In your conditional statement, the predicate i1[i+1] becomes i1[10] when i=9. You need to fix this.
Lastly, you can achieve your objective the following way too:
System.out.println("Enter 10 numbers");
int small=0;
for(int i=0; i<10; i++){
Scanner in=new Scanner(System.in);
int[] i1=new int[10];
int num=in.nextInt();
i1[i]=num;
}
Arrays.stream(i1).sorted().forEach(System.out::println);

Counting unique numbers from int array - Java [duplicate]

This question already has answers here:
counting occurrence of numbers in array
(6 answers)
Closed 8 years ago.
I am trying to build and array where the user enters numbers. Then at the end the program outputs a list of the entered numbers along side the amount of times each individual number was entered.
Currently I have:
package arraypractice;
import java.util.Scanner;
public class Entry {
private Scanner scan = new Scanner(System.in);
public void userInput(){
System.out.println("Please tell me the amount of numbers you will be $ entering: ");
int [] arr = new int[scan.nextInt()];
for(int i=0;i<arr.length; i++) {
scan = new Scanner(System.in);
System.out.println("Please enter a number: ");
while(scan.hasNextInt()){
int x = scan.nextInt();
arr[i]= x;
break;
}
}
for(int i:arr){System.out.println(i + " occurs");
}
}
}
For example this outputs:
run:
Please tell me the amount of numbers you will be $ entering:
2
Please enter a number:
25
Please enter a number:
21
25 occurs
21 occurs
BUILD SUCCESSFUL (total time: 10 seconds)
In a perfect world I would like to output to look like this:
run:
Please tell me the amount of numbers you will be $ entering:
2
Please enter a number:
25
Please enter a number:
21
Number Times Entered
25 occurs 1
21 occurs 1
BUILD SUCCESSFUL (total time: 10 seconds)
I am not sure how to implement this. A second array? If so how? Also is there a way I can get the headings Number and Times Entered?
You are not seeing a main method because it is in another class that instantiates this.
Thanks.
To get a heading you just put a println() method before you run the for loop to print out the array.
It seems like you want to format the print out. To do that you would need to use
printf("%6d%10s%6d", i, "occurs", array[i])
That's the general idea.

scan the array input [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Array sorting input
Implement a program to process votes for 5 candidates in a talent
contest.
The program should use a String array to hold the names of the 5
candidates and an integer array to record the number of votes for each
contestant.
It should prompt the user to enter the number of the candidate they
wish to vote for (in the range 0 – 4), until -1 is entered, which
signifies the end of voting. An error message should be output if the
candidate selected is not in the required range.
At the end of voting, the program should sort the votes into
descending order and output them, before outputting messages showing
who was in 3rd, 2nd and 1st place
Well, so far I had some failures that's all. I will not have any problem with sorting and swapping the input. But the input itself is a pain for me.
//exam result processing - using selection sort
import java.util.*;
public class VoteCount {
public static void main(String[] args) {
//create empty array
int[] votes = new int[5];
//input data
input(votes);
}
public static void input(int[] votes)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Enter vote number of the candidate results: ");
int votecount = kybd.nextInt();
while (votecount !=-1)
{
votes[votecount]++;
System.out.println("Candidate" + votes +"Has" +votecount + "votes");
}
}
}
you have to read the user's input inside the while cycle, like this:
Scanner kybd = new Scanner(System.in);
System.out.println("Enter vote number of the candidate results: ");
int votecount = kybd.nextInt();
while (votecount !=-1)
{
votes[votecount]++;
System.out.println("Candidate "+names[votecount]+" Has "+votes[votecount]+" votes");
System.out.println("Enter vote number of the candidate results: ");
votecount = kybd.nextInt();
}
in additional, "votes" is an array, so printing in will give you something like "0#562fb45", so let's say you wil create some "names" array, which will hold the candidates names, like this for example:
String names = {"Peter", "Tomas", "Jonny", "Mark", "Jane"};
You should use kybd.hasNext() to test whether there is any more vote number. and you can input in the terminal like this:
0,1,2,1,3
and modify while() to:
while(kybd.hasNext())
there is no need of -1 to end input, and you have to input all vote number in one line. you can use <space>、comma or <Tab> to split vote numbers.

Categories