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);
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
Expected output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Here are the distinct numbers 1 2 3 4 5
output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 5
out of bounds for length 5
at Main.main(Main.java:26)
/*
Johnny Santamaria
CS 111B Assignment 5 - deDup
This program gives you instructions to remove duplicate numbers in an array
*/
class Main {
public static void main(String[] args) {
int[] numArray;
int index = 0;
int num;
if (args == null || args.length < 1) {
System.out.println("Usage: java Main 1 2 3 4 5 5 to remove duplicates from the numbers 1 2 3 4 5 5");
return; //exit function
}
//finds integers in command line
index = args.length;
numArray = new int[index];
//convert to integers to actually make the array
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[index] = num;
index++;
}
int uniqueIndex = deDup(numArray, index);
}
public static int deDup(int[] numArray, int index) {
if (index == 0 || index == 1) {
return index;
}
//creates new index to store unique numbers
int uniqueIndex = 0;
//checks each number in the array to remove duplicates to make a new index
for (int i = 0; i < index - 1; i++) {
//deletes a number in the index of the array then reformats them
if (numArray[i] != numArray[i + 1]) {
numArray[uniqueIndex++] = numArray[i];
}
}
numArray[uniqueIndex++] = numArray[index - 1];
System.out.println("Here are the distinct numbers: " + numArray[uniqueIndex]);
return uniqueIndex;
}
}
The exception message indicates that you are trying to access an index that does not exist:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5 at Main.main(Main.java:26)
Illegal access occurs on this line:
numArray[index] = num;
The reason is that in numArray there is no index with the value of the index variable.
PS: note that on line 19 you assign the length of args to the variable index.
The problem is that you define these values:
index = args.length;
numArray = new int[index];
and then in the first loop iteration you access
numArray[index] = num;
which is not a valid index since it is too big by 1.
The real problem here is that you are using index as a running variable in your loop, but it is not set to the starting value of 0. You are using the same variable for two different purposes.
Either
set index = 0; before the loop or
use a different variable in your loop, such as i:
int i = 0;
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[i++] = num;
}
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]
My scanner is not accessing last line of my text file correctly, thus is storing the last line of the text file as all 0's into my 2D array instead of what is actually there. I believe I have provided everything that would give context as to what is going wrong, but if more info is needed I can update this question, thanks in advance.
//Creates 2-d array object, stores values from file.
public DominoSort (String fileName) throws java.io.FileNotFoundException{
this.grid = new int [7][8]; //2-d array to hold values from text file
Scanner br = new Scanner(new File(fileName));
String line = br.nextLine();
int r = 0;
int c = 0;
while (br.hasNextLine) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
//this.setS = new ArrayList<>();
//this.pairMappings = new ArrayList<ArrayList<dominoLocation>>();
br.close();
}
//Print grid function, prints out the grid
public void printGrid() {
for(int r = 0; r < this.grid.length; r++) {
System.out.println("");
for(int c = 0; c < this.grid[r].length; c++) {
System.out.print(this.grid[r][c] + " ");
}
}
System.out.println("");
}
//Driver for checking
public static void main(String[] args) throws IOException {
// String line;
//System.out.println(new File(".").getAbsolutePath());
Scanner input = new Scanner(System.in); //get textfile name from user input
System.out.print("Enter the file name: ");
String fileName = input.next();
DominoSort dom = new DominoSort(fileName); //this call populates the 2-d array object
//dom.solvePuzzle(6);
dom.printGrid(); //prints 2d array for output
//dom.solvePuzzle(6);
}
text file used for testing / expected output:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
2 0 3 2 5 0 5 4 {Notice this line}
actual output:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
0 0 0 0 0 0 0 0 {this line is not right}
Your problem lies within the nested while/for loop. It reaches the end condition before all the lines are read. (The nextLine() method doesn't have any more lines before you read the last line). You can see this by putting an extra 1 or 2 lines in your file at the very end, making it show the last lines.
There are a few ways to fix it, one of them is by just adding on an extra for loop after the while loop to compute the last line individually:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
or alternatively, don't increment the line on the first run:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
if (r != 0)
line = br.nextLine();
r++;
c = 0;
}
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
how do I make a loop that checks 1, 4 times and then moves to 2, and checks it 4 times, and moves to 3, and checks it 4 times.
For example:
//Btw, isNextFree is a boolean that returns true or false if the next line is free.
while(linenumber.isNextFree()){
int linenumber=1;
username = line(linenumber,usernamefile);
linenumber+=1;
}
So, what that loop does is it checks linenumber of usernamefile.txt and stores that value in a hashmap, I need to check use that string value in line one which is stored in that hashmap to make a 4 strings on what is on linenumber 1 on username file concatenate with 1 same passwordstring on passwordfile.txt.
By the way, I'm using scanner, so the line and linenumber.isNextFree doesn't exist, it is like scanner's .isNext basically.
I don't understand the second part of the question, for the first:
for(int i=1; i<4; i++)
{
for(int j=1; j<5; j++)
{
//Do somethings for check
//Example
System.out.println("It's "+ i + " = " j ");
}
System.out.println(""); //only a new line like \n
}
With this code, it do somethings with 1, 4 times
after do something with 2, 4 times
and after do somethings with 3, 4 times
the output is:
It's 1 = 1
It's 1 = 2
It's 1 = 3
It's 1 = 4
It's 2 = 1
It's 2 = 2
It's 2 = 3
It's 2 = 4
It's 3 = 1
It's 3 = 2
It's 3 = 3
It's 3 = 4
I hope this helps.