Getting NZEC error in SPOJ with Java for this Code - java

This is my answer for half of half question in SPOJ( Question ID :12156) . I'm a beginner in JAVA. Please Help why am i getting an error. I'm able to get an expected answer while compiling in Ideone. Thanks
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan =new Scanner(System.in);
String[] name= new String[10];
int size,count;
String temp,news;
char[] chars= new char[20];
temp=scan.nextLine();
count=Integer.parseInt(temp);
for(int i=0;i<count;i++)
{
name[i]=scan.nextLine();
}
for(int j=0;j<count;j++)
{
news=name[j];
size=news.length();
chars=news.toCharArray();
for(int k=0;k<size/2;k=k+2)
{
System.out.print(chars[k]);
}
System.out.println();
}
}
}

Pay attention to the following points in the problem description:
In the first line of input your are given the positive integer t
(1 <= t <= 100) - the number of test cases.
In your code, you can handle 10 (and not 100) strings at maximum.
String[] name = new String[10];
In the each of the next t lines, you are given a sequence of 2*k
(1 <= k <= 100) characters.
In your code, you can handle 20 (and not 200) characters at maximum.
char[] chars = new char[20];

I did attempt same question half of half at SPOJ, my code is accepted.
I think array initialisation should be based on input.
import java.util.Scanner;
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
int testCase = scan.nextInt();
scan.nextLine();
String[] inputStringArray = new String[testCase];
for (int x = 0; x < testCase; x++) {
String input = scan.nextLine();
input = input.replaceAll("\\s+", "");
inputStringArray[x]=input;
System.out.println("#-"+x);
}
for(int y=0;y<testCase;y++){
String text = inputStringArray[y];
char[] inputArray = text.toCharArray();
int len = inputArray.length/2;
for(int z=0;z<len;z=z+2){
System.out.print(inputArray[z]);
}
System.out.println("");
}
}
}

Related

Problems with iterated nextLine function

I am trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);

HackerRank says ~ no response on stdout ~

So I was solving this Question on HackerRank (Project Euler Q1) link here, and have used the following code to solve it
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int T = 0;
ArrayList<Integer> N = new ArrayList<Integer>();
String[] Input = args;
if (args.length>1){
T = Integer.parseInt(args[0]);
if(T<1||T>Math.pow(10,6))
System.exit(0);
}
if (args.length-1 == T){
for (int i=1;i<args.length;i++){
N.add(Integer.parseInt(args[i]));
int sum3=0,sum5=0,sum15=0;
int count=0;
while (count<N.get(i-1)){
sum3+=count;
count+=3;
}
count =0;
while (count<N.get(i-1)){
sum5+=count;
count+=5;
}
count =0;
while (count<N.get(i-1)){
sum15+=count;
count+=15;
}
N.set(i-1,(sum3+sum5-sum15));
}
}
for(int j=0;j<N.size();j++)
System.out.println(N.get(j));
}
}
This gives me the following output on an IDE :
23
2318
While Inputting :
2
10
100
And this matches the expected output on HackerRank, but however When I use this code on the website, It says :
Input (stdin)
2
10
100
Your Output (stdout)
~ no response on stdout ~
Expected Output
23
2318
Compiler Message
Wrong Answer
One thing I could observe was I couldn't print anything from inside a loop on HackerRank. What would the solution to this be?
You're not reading from STDIN the way HackerRank wants you to. Instead of getting your input from args, you should be doing this kind of thing:
Scanner sc = new Scanner(System.in);
int numberOfTestCases = sc.nextInt();
and so on.
I just ran this code, compiled fine and submitted it.
import java.io.*;
public class Solution{
public static void main(String[] args) throws IOException
{
//Input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int[] N = new int[T];
for(int t = 0; t < T; N[t++] = Integer.parseInt(br.readLine())){
}
br.close();
br = null;
//Solve
long[] V = new long[T];
for(int t = 0; t < T; ++t){
int n = N[t] - 1;
V[t] = 3*nSum(n/3) + 5*nSum(n/5) - 15*nSum(n/15);
}
//Print
StringBuilder sb = new StringBuilder();
for(int t = 0; t < T; sb.append(V[t++]).append("\n")){
}
System.out.print(sb);
}
public static long nSum(int n){
long v = n;
return (v*v + v) >> 1;
}
}
I had the same problem with a php code and I used return instead of echoing for your case replace sout with return

Changing input so in can take any length of string, problems with output

Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.

Java, basic array error

I am trying to do a Java program that will let me input 10 words, and then the words should be repeated in reverse order (the last first etc).
This is my current code:
import java.util.Scanner;
import java.lang.String;
public class Words {
public static void main(String[] args){
String word[] = {};
for(int x = 0; x < 10; x+=1) {
System.out.println("Input any word");
Scanner input = new Scanner(System.in);
word = new String[] { input.next() };
}
for(int y = 9; y >= 0; y-=1) {
System.out.println(word[y]);
}
}}
It gives me the following error when trying to compile:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at Words.main(Words.java:21)
I am new to Java and would appreciate help, thanks in advice.
That's not how arrays work.
Change String word[] = {}; to String word[] = new String[10];
Also, change word = new String[] { input.next() }; to word[x] = input.next().
It is also a good idea to move Scanner input = new Scanner(System.in); outside of the for loop. You should read up on how arrays work to make sure this doesn't happen again.
You could try use an ArrayList to do this like so:
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList al = new ArrayList();
do{
System.out.println("Enter word");
String word = sc.nextLine();
al.add(word);
if(al.size()==10){
System.out.println("Words in reverse order");
for(int i = al.size()-1; i>= 0; i--){
System.out.println(al.get(i));
}
}
}while(al.size()<10);
}
}
I think this answers your question properly.
All the best
Sean

How can I print my array in a certain way? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm wanting to print my arrays in a list. That will look like this.
Word: Count:
Myths 2
Of 15
Babylonia 25
I can't seem to figure out how to print it the correct way, here is the code I have so far. Any help is appreciated, thanks!
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class Program6 {
static String[] stringArray = new String[100];
static int[] intArray = new int[100];
static String fileName = "myths.txt";
static int currentWordIndex = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(fileName));
while (input.hasNext()){
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if(stringArray[i].equals(word)){
alreadyExists = true;
intArray[i]++;
break;
}
}
if(!alreadyExists && currentWordIndex <100){
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
}
}
Use a format and use a loop
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word:\t\tCount:");
for (int i = 0; i < stringArray.lengthl i++){
System.out.printf("%s\t\t%d\n", stringArray[i], intArray[i]);
}
Edit with right aligntment
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < array1.length; i++) {
System.out.printf("%10s%10d", array1[i], array2[i]);
System.out.println();
}
Edit: Using a method for other books
public static void main(String[] args) throws FileNotFoundException{
printCounts("myth.txt", "Babylonia and Assyria");
System.out.println();
printCounts("someOther.txt", "Some Other Title");
System.out.println();
printCounts("another.txt", "Another Title");
System.out.println();
}
public static void printCounts(String filename, String title) throws FileNotFoundException {
String[] stringArray = new String[100];
int[] intArray = new int[100];
int currentWordIndex = 0;
Scanner input = new Scanner(new File(filename));
while (input.hasNext()) {
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if (stringArray[i].equals(word)) {
alreadyExists = true;
intArray[i]++;
break;
}
}
if (!alreadyExists && currentWordIndex < 100) {
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println(title);
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < stringArray.length; i++) {
System.out.printf("%10s%10d", stringArray[i], intArray[i]);
System.out.println();
}
}
When you are doing
System.out.println();
it is actually printing a new line at the end of your output.
Try using
System.out.print("foo ");
System.out.println("bar");
Have look at this page which explains the use of System.printf to align columns.
System.out.printf( "%-15s %15s %n", heading1, heading2);
Your arrays have 100 elements, so lots of Zeros get printed, use Arrays.copyOf to create smaller arrays.
For table format, use printf.
So you should replace the following code:
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
with:
String[] stringArray2 = Arrays.copyOf(stringArray, totalWordCount);
int[] intArray2 = Arrays.copyOf(intArray, totalWordCount);
stringArray = null;
intArray = null;
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("\n%15s%15s", "Word:","Count:");
for (int i = 0; i < stringArray2.length; i++){
System.out.printf("\n%15s%15d", stringArray2[i], intArray2[i]);
}
You have to right justify your columns. According to this stackoverflow question, columns left justified with a negative sign in front of them and right justfified without. You want your print statement to look something like this:
System.out.printf("%60s %3d", stringArray[i], intarray[i]));
You can vary the column width this way.
In addition: Someone mentioned you can avoid printing a line at the end of each statement by using print instead of println.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Program6 {
static String fileName = "myths.txt";
private static Scanner input;
public static void main(String[] args) throws FileNotFoundException {
input = new Scanner(new File(fileName));
Map<String, Integer> map = new HashMap<String, Integer>();
while (input.hasNext()){
String word = input.next();
if ( map.containsKey(word) ){
int temp = map.get(word) + 1;
map.put(word, temp);
} else {
map.put(word, 1);
}
}
// get all the set of keys
Set<String> keys = map.keySet();
// iterate through the key set and display key and values
System.out.printf("%-10s\t\t%s\n", "Word", "Count:");
for (String key : keys) {
System.out.printf("%-10s\t\t%d\n", key, map.get(key));
}
}
}

Categories

Resources