can I print empty int array withou zero aprearing in java - java

this is my code can i print my array without zero if it is empty?
import java.util.Arrays;
import java.io.*;
public class Stacks{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("what is the size of your stack? :");
int size = Integer.parseInt (br.readLine());
int get = size;
int[] Array = new int[size];
System.out.println("type: push , pop , exit");
System.out.println("remember! you can EXIT anytime");
System.out.println(Arrays.toString(Array));
/*there still a code here but this is just what i needed to show..*/
}
}
please help me.. PS I don't want to import stacks..

Since your not using your Array as an array, but ultimately as a stack, you will not want to use Arrays.toString() which is designed for printing arrays as arrays. You need to write your own method, bearing in mind the stack your creating maybe smaller than the size of the array you're populating.
Without knowing how you're stack is implement, a basic model would be
public static String arrayAsStack(int[] array, int elements_in_stack) {
String out = "[";
for(int i=elements_in_stack-1; i>=0; i--)
out += arrary[i] + " ";
out+="]";
return out;
}
This method of course may not be right, depending on the way you format your stack-array. Note the elements_in_stack should start at 0. Once you get the right implementation of this method for you stack you can just print the results in the natural way.

if you just want your array to be displayed without the zeros you can just use a if statement.
for( int i = 0; i < Array.length; i ++ ){
if( Array[i] != 0 ){
System.out.print( Array[i] + " ");
}
}
This will just iterate through your array and test if the value is zero. If it is not it will display the value, if it is, it disregards it.

instead of using int type i created it using object
import java.util.Arrays;
import java.io.*;
public class Stacks{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("what is the size of your stack? :");
int size = Integer.parseInt (br.readLine());
int get = size;
Object[] Array = new Object[size];
System.out.println("type: push , pop , exit");
System.out.println("remember! you can EXIT anytime");
/* here i use the code of Ryan*/
for( int i = 0; i < Array.length; i ++ ){
if( Array[i] != null ){
System.out.print( Array[i] + " ");
}
}
/*there still a code here but this is just what i needed to show..*/
}
}
now i can display 0 if I input it..

Related

Accessing index values before and after symbol from input

I am trying to take the input and if there is an # symbol in the input then it finds the maximum of the integers before and after the # symbol. The maximum part I have no problem with but I do not know how to access and find the values before and after the # symbol.
import java.util.Scanner;
public class Max_Min {
public static void main(String[] args) {
//gets keyboard
Scanner keyboard = new Scanner(System.in);
//puts input into string
String inputString = keyboard.nextLine();
//splits string between characters
String[] splitInput = inputString.split("");
for (String s : splitInput) {
if(s.equals("#")){
//computes the maximum of the two integers before and after the #
}
}
//close keyboard
keyboard.close();
I did do a search to find something simliar (and im sure there is something) but could not find anything. If someone could help that would be great!
Try with this:
for (int i = 0; i < splitInput.length; i++){
if (splitInput[i].equals("#") && i != 0 && i != splitInput.length -1){
int max = Math.max(Integer.parseInt(splitInput[i - 1]), Integer.parseInt(splitInput[i + 1]));
}
//...
}
You could try:
String[] splitInput = inputString.split("#");
which would split your string at the #s.
Then you can do a iteration over your splitInput array and do a .length on each index.
You have written the simple for loop, with which you can only access the string, but not its index in the array. If you had the index, you could write:
int possibleMax = Integer.parseInt(splitInput[i - 1]) + Integer.parseInt(splitInput[i + 1]);
To get the index, there are two ways:
for (int i = 0; i < splitInput.length; i++) {
String s = splitInput[i];
...
}
Or:
int i = 0;
for (String s : splitInput) {
…
i++;
}
I don't like either version because both are more complicated than absolutely necessary, in terms of written code. If you would use Kotlin instead of Java, it would be:
splitInput.forEachIndexed { i, s ->
…
}
In Java this could be written:
forEachIndexed(
splitInput,
(i, s) -> …
);
The problem in Java is that the code inside the … cannot update the variables of the enclosing method. I'm not sure whether this will ever change. It would be possible but needs a lot of work by the language committee.
A simple way to do this would be
String input = "12#23";
String [] arr = input.split("#");
if (arr.length == 2) {
System.out.println("Max is "+Math.max(Integer.valueOf(arr[0]),Integer.valueOf(arr[1])));
}

Time limit exceeded even with best approach(Java)

Even if I think that I solved a competitive programming problem from HackerEarth with the best approach, all tests exceed the time limit. I really do not know how to optimize it further because it is just an easy exercise.
My approach: iterate over all array members than add them to a HashMap which stores their occurrences. After that simply read the query numbers and get their occurence from the HashMap.
This is my solution:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
//go through all test cases
for (int i = 0; i < t; i++) {
Map<Integer, Integer> map = new HashMap<>();
String[] inputs = br.readLine().split(" ");
int N = Integer.parseInt(inputs[0]);
int Q = Integer.parseInt(inputs[1]);
inputs = br.readLine().split(" ");
//read array
for (int j = 0; j < N; j++) {
int x = Integer.parseInt(inputs[j]);
Integer value = map.get(x);
//if number is already in hashmap then increment its count
//else put it into the map with a count of 1
if (value == null) {
map.put(x, 1);
} else map.put(x, value + 1);
}
//iterate through the queries and get their occurences from the map
for (int j = 0; j < Q; j++) {
int x = Integer.parseInt(br.readLine());
Integer value = map.get(x);
if (value == null) {
System.out.println(0);
} else System.out.println(value);
}
}
}
}
My question is: what can be the problem with my approach? Why does it run out of time?
Ok, so the problem is not so obvious. I took a look at the input files and they are huge so you have to use some really fast method for writing to the console(many test cases -->> many answers). You can use PrinteWriter for that.
Working solution:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
//go through all test cases
for (int i = 0; i < t; i++) {
Map<Integer, Integer> map = new HashMap<>();
String[] inputs = br.readLine().split(" ");
int N = Integer.parseInt(inputs[0]);
int Q = Integer.parseInt(inputs[1]);
inputs = br.readLine().split(" ");
//read array
for (int j = 0; j < N; j++) {
int x = Integer.parseInt(inputs[j]);
Integer value = map.get(x);
//if number is already in hashmap then increment its count
//else put it into the map with a count of 1
if (value == null) {
map.put(x, 1);
} else map.put(x, value + 1);
}
//iterate through the queries and get their occurences from the map
for (int j = 0; j < Q; j++) {
int x = Integer.parseInt(br.readLine());
Integer value = map.get(x);
if (value == null) {
pr.println(0);
} else pr.println(value);
}
}
pr.close();
}
}
Yes, I know that it is strange that the exercise itself is not so hard, but reading the input and writing the result is the big part of it.
The problem with your approach is primarily it's use of BufferedReader, and the consequential information parsing you're preforming. Try an approach with scanner.
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int T = s.nextInt();
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<T;i++)
{
StringBuilder sb=new StringBuilder();
int N=s.nextInt();
int Q=s.nextInt();
int[] arr=new int[N];
for(int j=0;j<N;j++)
{
arr[j]=s.nextInt();
if(map.containsKey(arr[j]))
{
map.put(arr[j],map.get(arr[j])+1);
}
else
map.put(arr[j],1);
}
for(int k=0;k<Q;k++)
{
int X=s.nextInt();
if(map.containsKey(X)){
sb.append(map.get(X)+"\n");
}
else{
sb.append(0+"\n");
}
}
System.out.println(sb.toString());
map.clear();
}
}
}
This will remove a lot of the unnecessary parsing you are doing with:
String[] inputs = br.readLine().split(" ");
int N = Integer.parseInt(inputs[0]);
int Q = Integer.parseInt(inputs[1]);
inputs = br.readLine().split(" ");
Please look at Scanner vs. BufferedReader to understand why Scanner is situationally faster here. Essentially BufferedReader is faster in it's ability to simply read the lines, but when you use BufferedReader here, you are then forced to use Integer.parseInt(...) and br.readlines().split(" ") to parse the information you need from the input; however, scanner has built in parsing mechanisms that can read and parse the data asynchronously. As you will see, this approach passes the test in 4-8 seconds. Additionally you could benefit from using StringBuilder, and not using:
Integer value = map.get(x);
if (value == null) {
pr.println(0);
} else pr.println(value);
With the built in method map.containsKey(x).
Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special
parsing.
In fact you can pass a BufferedReader to a scanner as the source of
characters to parse.
Furthermore:
A scanner on the other hand has a lot more cheese built into it; it
can do all that a BufferedReader can do and at around the same level of
efficiency as well. However, in addition a Scanner can parse the
underlying stream for primitive types and strings using regular
expressions. It can also tokenize the underlying stream with the
delimiter of your choice. It can also do forward scanning of the
underlying stream disregarding the delimiter!
There is a large difference in runtime when you have to call
inputs = br.readLine().split(" "); and Integer.parseInt(..) multiple times, versus simply calling s.nextInt(). You are already reading the data with br.readLine(), when you call Integer.parseInt(...) the data is read again by the parseInt() function.

Cycle while with scanner hasNext()

I have a problem when I try to run my work.
I have to put in some numbers by console and It should arrange in ascending order them and save to an array.
I thought that method hasNext worked well with String.nextLine(), but it seems to still in loop.
thanks for help
import java.util.Scanner;
public class OrdinamentoMaggiore{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Digita dei numeri e te li mettero' in ordine crescente: ");
String Numeri = sc.nextLine();
int dimArray = 0;
while (sc.hasNext(Numeri)){
dimArray++;
System.out.println("Dimensione array: " + dimArray);
}
int min = 0, max = 0, temp;
int[] mioArray = new int[dimArray];
for (int i = 0; i <= mioArray.length; i++){
mioArray[i] = Integer.parseInt(sc.next(Numeri));
}
for (int j = 0; j <= mioArray.length; j++){
for (int h = 1; h <= mioArray.length; h++){
if (mioArray[j] < mioArray[h]){
continue;
}
else {
temp = mioArray[j];
mioArray[j] = mioArray[h];
mioArray[h] = temp;
}
}
}
System.out.println("Min: " + mioArray[0]);
System.out.println("Max: " + mioArray[dimArray]);
sc.close();
}
}
The problem is that you are reading the first line of input into the variable Numeri. Then, you are calling hasNext on Numeri which isn't working the way you think it is. Scanner.hasNext is defined here as:
Returns true if the next token matches the pattern constructed from
the specified string.
So it is using the string in Numeri as the pattern it needs to match. Definitely not what you want.
I would recommend a list and doing something like this:
List<Integer> numberList = new ArrayList<>();
while (sc.hasNextInt()) {
numberList.add(sc.nextInt());
}
Collections.sort(numberList);
A list is nice because you don't have to explicitly tell it the size. That avoids your first loop. Now, the loop goes continues reading from System.in until it encounters something that isn't an integer and adds them to the list.
Finally, it uses Collections.sort to sort the list. How beautiful is that? Your whole program can be reproduced in just a few lines. Definitely try and learn the libraries and functions that are available to you. It can save you a lot of time and effort. Let me know if you have questions.

Sorting Strings as inserted into array in Java

I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}
There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.
If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.
Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;

How to use portion of an array

Sorry if everyone sees me post a lot of silly questions today (just a preface). However this is the final for a summer class and my teacher stopped caring/explaining how to do things for my first coding class.
For this project I have to print a list of integers from a .dat file into a program in reverse order with a max of 40 possible values in the array (Did all that) The problem I am encountering is that he said the program should also be flexible enough to deal with less than 40 values. However given my current code I always encounter an error saying "nosuchelementexception". Any help would be greatly appreciate. Below is a copy of what I have:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array with 40 cells
int k; // creating counter integer
Scanner InputFile = new Scanner( new FileReader("temp.dat")); // input file you wish to open.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
for (k = Values.length - 1 ; k >= 0 ; k--)
System.out.println("Cell " + k + " contains the value " + Values[k]);
InputFile.close();
}
}
The problem you are having is that the length attribute of an array refers to the declared length, not the amount of data in it.
When you try to use the length (in this case 40) to control the loop you use for reading data, you will get an error if there are fewer elements to read.
What you want to do is read more input only while there exists more input to get:
int k = 0;
while (inputFile.hasNextDouble()) {
Values[k++] = inputFile.nextDouble();
}
Also, consider using an ArrayList instead of an array. The ArrayList class allows you to store a dynamic amount of data, so you don't have to worry about pre-allocating storage space:
ArrayList<Double> values = new ArrayList<>();
while (inputFile.hasNextDouble()) {
values.add(inputFile.nextDouble());
}
You can use a while loop and a counter
import java.io.*; // Imports any file operation (ie Reading or Writing)
import java.util.Scanner; // Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called Values
Values = new double [40]; // establishing array has 40 cells
int counter = 0; // creating counter integer
Scanner inputFile = new Scanner( new FileReader("temp.dat")); //input file you with to open.
while(inputFile.hasNextDouble()){
Values[counter] = InputFile.nextDouble();
counter++;
}
for (i = counter - 1 ; i >= 0 ; i--)
System.out.println("Cell " + i + " contains the value " + Values[i]);
InputFile.close();
}
}
If you do not have to use an Array, use an ArrayList<Double>. This allows you to call values.add(value) to add to the list. The length is variable and you can use your same code (just replace values[i] with values.get(i))
However, if you do have to use arrays, created a method that adds to the array. Start with a 0 length array, and when an element is added, create a new array of length+1, then copy the old elements in, and add the new element at the end.
There are many other ways to go about this, but these two allow you to use your existing working code.
Array approach:
values = new double[0];
public void add(double x){
double[] temp = new double[values.length +1];
for(int i =0; i< values.lenght; i++){
temp[i] = values[i];
}
temp[temp.length-1] = x;
values = temp;
}
you should use an arrayList instead so you don't have to initially set the size of the array. This would make it so that you never have empty elements in the array.
Another option would be to initialize the array with placeholder values like -1, and then only perform the switch if the value is not -1.
Add a counter that keeps track of how many item you put into the array and use that to determine where to stop when you go to print them out.
Is there 40 elements in your .dat file. If there isnt your code probably gave the exception.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
If your .dat file doesn't contain 40 elemennts then value[39] can't be filled in.
An Array has a fixed size after initialising it, so you may want to use dynamic datastructure or instead use a while loop as posted below. I personally would recommend an ArrayList in this case.
You should also use the method
Scanner.hasNext() or in your particular case Scanner.hasNextDouble() Docs
to get any new elements.
So your program would then look like this:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
import java.util.ArrayList;
public class program3
{
public static void main(String [] ars) throws IOException
{
ArrayList<Double> doubles = new ArrayList<Double>();
Scanner inputFile = new Scanner( new FileReader("temp.dat"));
while (inputFile.hasNextDouble()) {
doubles.add(inputFile.nextDouble());
}
inputFile.close();
for (Double value : doubles) {
System.out.println(value);
}
}
}
Java has convenient methods in it's Collections class to allow sorting. You may want to check this out if you haven't already.
I admire your grit getting on Stack Overflow.
To reward you here's your answer.
The first for loop you have iterates over your new, empty array. That would be find except you are RETRIEVING information from the Scanner object, InputFile.
So you should in fact be iterating over that object! Not your array. No shame though. Classic mistake.
Here's my version of your code:
import java.io.FileReader;
import java.io.IOException; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main( String [] ars ) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array has 20 cells
int k; // creating counter integer
//input file you with to open.
Scanner InputFile = new Scanner( new FileReader( "temp.dat" ) );
for ( k = 0; InputFile.hasNextDouble(); k ++ )
Values[k] = InputFile.nextDouble();
for ( k = Values.length - 1; k >= 0; k-- )
System.out.println( "Cell " + k + " contains the value " + Values[k] );
InputFile.close();
}
}
Hope this helps!

Categories