No line found at java.util.Scanner.nextLine(Scanner.java:1540) - java

I'm trying to get a program that checks if a string input from the user is a palindrome (task from CodeAbbey). When I type myself input data, it works well, but if strings are put automatically by the site, I'm getting this error:
Exception:
Exception in thread "main" java.util.NoSuchElementException: No line
found at java.util.Scanner.nextLine(Scanner.java:1540) at
Palindromes.main(Palindromes.java:13)
The code:
public class Palindromes {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanStr = new Scanner(System.in);
//Number of tests
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
//Getting string
String s = scanStr.nextLine();
//Variable for number of letters in string
int letters = 0;
//Getting number of letters in string
for (int j = 0; j < s.length(); j++) {
if (Character.isLetter(s.charAt(j)))
letters++;
}
//Array with string characters
char[] characters = new char[letters];
//Counter
int a = 0;
//Put chars from string to array
for (int j = 0; j < s.length(); j++) {
if (Character.isLetter(s.charAt(j))) {
characters[a] = s.toLowerCase().charAt(j);
a++;
}
}
//Counters
int x = 0;
int y = characters.length - 1;
//Variable for result
char res = 'Y';
//If the string is a palindrome
do {
if (characters[x] != characters[y])
res = 'N';
x++;
y--;
} while (x <= y);
//Prints result
System.out.print(res + " ");
}
}
}

Related

Sorting empty and word array in java

I want to write a code which can sort char array element. But the problem is where i want to sort 'a' before 'aa' element and I don't know how to write this part. It always sort 'aa' before 'a'. At first it get inputs from user and if we write '0' it will print sorted array.
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
You have to consider that 'aa' is not a char, instead 'a' is a char.
If you want to sort strings the code is nearly okay.
Here an example:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int num = 0;
String[] arr = new String[1000];
String index = "";
Scanner myObj = new Scanner(System.in);
for(int i = 0; i < 1000; i++){
arr[i] = myObj.nextLine();
if(arr[i].equals("0")){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i].compareTo(arr[j]) < 0){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
System.out.print("[ ");
for(int i = 0; i < num; i++){
System.out.print(arr[i] + " ");
}
System.out.println("]");
}
}
Input:
aaaaaaaa
aaaaaaa
aaaaaa
aaaaa
aaaa
aaa
aa
a
0
Expected Output:
[ a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa ]
It is only sorting by the first char of an entered word.
Thus it seems like the input-order is preserved.
Issue
Adding some debug-prints shows the comparison of first-char is leading to incorrect or unwanted aa before a case:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
System.out.printf("Debug [%d]: '%s' \n", i, String.valueOf(arr[i]));
for(int j = 0; j < i; j++){
System.out.printf("Compare '%s' < '%s' = %s\n", arr[i][0], arr[j][0], (arr[i][0] < arr[j][0]));
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
Output:
a
Debug [0]: 'a'
aa
Debug [1]: 'aa'
Compare 'a' < 'a' = false
0
a
aa
Refactored and solved
I just added a bit output to interact with user.
Also refactored a bit (extract into methods, and control length of arrays with a configurable constant).
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner myObj = new Scanner(System.in);
public static void main(String[] args) {
char[][] arr = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int num = readArray(0, arr);
System.out.printf("Printing %d elements:\n", num);
printArray(num, arr);
}
private static int readArray(int num, char[][] arr) {
char[] index;
int i;
for (i = 0; i < LENGTH; i++) {
arr[i] = readChars();
if (arr[i][0] == '0') {
break;
} else {
num++;
}
for (int j = 0; j < i; j++) {
if (String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
return num;
}
private static void printArray(int num, char[][] arr) {
int i;
for (i = 0; i < num; i++) {
System.out.println(arr[i]);
}
}
private static char[] readChars() {
return myObj.next().toCharArray();
}
}
Output is as expected (a before aa):
Enter elements (each on a new line, 0 stops):
z
aa
b
a
0
Printing 4 elements:
a
aa
b
z
How it works
Entire array compared (chars in sequence) instead only the first char of each array.
before:
arr[i][0] < arr[j][0]
after:
String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0
Bonus Tip: Naming can help to spot logical bugs
When renaming the methods and variable names it may get a bit clearer what the program does, we call it semantics:
myObj becomes scanner
i becomes index or wordIndex or lineIndex and lastLineIndex
j is actually a character-index ... but in this short scope it should can be self-evident
char-arrays can be lines or words
num becomes length of lines or countLines
and all the method-names are adjusted in semantics to operate on lines, expressed by name <verb>Lines
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
char[][] lines = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int countLines = readLines(lines);
System.out.printf("Printing %d elements:\n", countLines);
printLines(lines, countLines);
}
private static int readLines(char[][] lines) {
int linesRead = 0;
for (int lineIndex = 0; lineIndex < LENGTH; lineIndex++) {
lines[lineIndex] = readLine();
if (lines[lineIndex][0] == '0') {
break;
} else {
linesRead++;
}
sortLines(lines, lineIndex);
}
return linesRead;
}
private static void sortLines(char[][] lines, int lastLineIndex) {
for (int j = 0; j < lastLineIndex; j++) {
if (String.valueOf(lines[lastLineIndex]).compareTo(String.valueOf(lines[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
char[] line = lines[lastLineIndex];
lines[lastLineIndex] = lines[j];
lines[j] = line;
j = 0;
}
}
}
private static void printLines(char[][] lines, int length) {
for (int i = 0; i < length; i++) {
System.out.println(lines[i]);
}
}
private static char[] readLine() {
return scanner.next().toCharArray();
}
}

Runtime error on test 1 (Code Forces) but workes in netbeans

I am new to code forces, when i run this code in NetBeans its works correctly but when I submit it on code forces it gives me Runtime error on test 1. what is the wrong?
This is the problem
import java.util.Scanner;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String first = input.nextLine();
String second = input.nextLine();
input.close();
String first_line[] = first.split(" ");
String second_line[] = second.split(" ");
int first_numbers[] = new int[first_line.length];
int second_numbers[] = new int[second_line.length];
for (int i = 0; i < 2; i++) {
if (Integer.parseInt(first_line[i]) >= 1)
first_numbers[i] = Integer.parseInt(first_line[i]);
else
first_numbers[i] = 0;
}
for (int i = 0; i < second_line.length; i++)
if (Integer.parseInt(second_line[i]) >= 1)
second_numbers[i] = Integer.parseInt(second_line[i]);
else
second_numbers[i] = 0;
int x = 0;
try {
for (int i = 0; first_numbers[1] < second_numbers[i]; i++)
x++;
} catch (Exception ex) {
}
System.out.println(x);
}
What if you modify your last for loop as below
int x = 0;
for (int i=0; i<second_numbers.length; i++) {
if (first_numbers[1] < second_numbers[i])
x++;
}
why you split String int those
String first_line[] = first.split(" ");
String second_line[] = second.split(" ");
int first_numbers[] = new int[first_line.length];
int second_numbers[] = new int[second_line.length];
you can initialize int from the beginning and use it 2 int like the following
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int n = input.nextInt();
int cout = 0;
int[] arr = new int[k];
and here you are my complete solution for this problem from 2014
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int k = input.nextInt();
int counter = 0, tk = 0;
int a[] = new int[n];
for(int i = 0; i < n; ++i){
a[i] = input.nextInt();
if((i + 1) == k){
tk = a[i];
}
}
for(int i = 0; i < n; ++i){
if(a[i] > 0 && a[i] >= tk){
counter++;
}
}
System.out.println(counter);
}
i wish i can help
if i can advice you
try to make it simple as much as you can in these problem at beginning.

How to include spaces inside a cypher program?

The code asks if you want to encode or decode a message, then it asks for the message. It will work by this reference:
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 "
"kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 "
Therefore if you try to encode the letter 'a' for example, it will output the letter 'k'.
My problem is that I can't include any spaces when typing the message.
Here is my code:
import java.util.Scanner;
public class SecretMessage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter 1 to encode, 2 to decode, 3 to quit:");
int start = input.nextInt();
if (start == 3){
break;
}
System.out.println("Type your message:");
String test = input.next();
String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 ";
String enc = "kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 ";
char[] array = test.toCharArray();
char[] decoded = letters.toCharArray();
char[] encoded = enc.toCharArray();
int[] position = new int[array.length];
char[] end = new char[array.length];
if (start == 1){
for (int i = 0; i < test.length(); i++){
for (int j = 0; j < decoded.length; j++){
if (array[i] == decoded[j]){
position[i] = j;
}
}
}
for (int f = 0; f < test.length(); f++){
end[f] = encoded[position[f]];
}
for (int x = 0; x < test.length(); x++){
System.out.print(end[x]);
}
System.out.println(" ");
} else {
for (int i = 0; i < test.length(); i++){
for (int j = 0; j < encoded.length; j++){
if (array[i] == encoded[j]){
position[i] = j;
}
}
}
for (int f = 0; f < test.length(); f++){
end[f] = decoded[position[f]];
}
String output = new String(end);
System.out.println(output);
}
System.out.println(" ");
} while (1 ==1);
}
}

Checking characters in a string

I want to wrote a program which checks every character in a string. If the two characters are same in a row I want to increase count by 1. The program should scan all the characters and give us a value. T is for deciding how many String's we will enter.
For example: (input)
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Ouput
3
4
0
0
4
But I get 0
3
4
0
0
Could you help? What I have done wrong?
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)
{
int i,T,j,count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++)
{
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for(j = 0; j <= S.length() - 1; j++)
{
list[j] = S.charAt(j);
}
for(j = 1; j <= S.length() - 1; j++)
{
if(list[j - 1] == list[j])
{
count++;
}
}
System.out.println(count);
}
}
}
I think something like the below should help you out, It first requires a number of strings that will be entered and then in the entered string will count the number of times a character is the same as the previous character. It wont take a series of strings though, it will do them one by one, see the example output below:
public static void main(String[] args){
int numInput;
String inputString;
Scanner scanner = new Scanner(System.in);
numInput = scanner.nextInt();
for(int y = 0; y < numInput;y++){
inputString = scanner.next();
char[] chars = inputString.toCharArray();
int counter = 0;
char curr;
for(int x = 0; x < chars.length;x++){
curr = chars[x];
if(x>0){
if(chars[x-1] == curr){
counter++;
}
}
}
System.out.println("Count for string " + inputString + " was " + counter);
}
scanner.close();
}
Testing:
5
AASAAB
Count for string AASAAB was 2
AAAAAA
Count for string AAAAAA was 5
AAVAAD
Count for string AAVAAD was 2
MOOMOO
Count for string MOOMOO was 2
MAAAAAA
Count for string MAAAAAA was 5
Try this...
public static void main(String[] args) {
int i, T, j, count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++) {
scan = new Scanner(System.in);
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for (j = 0; j <= S.length() - 1; j++) {
list[j] = S.charAt(j);
}
for (j = 1; j <= S.length() - 1; j++) {
if (list[j - 1] == list[j]) {
count++;
}
}
System.out.println(count);
}
}

I have to fill a 2D array with characters and let people search for words (Java)

So I have to fill a 2D array with chars, print out the array, let people search for words, and then print out the number of instances of that word and the array with the instances of that word highlit.
here is my code so far:
import java.util.Scanner;
import java.util.*;
public class testSearchMatrix {
public static void printArray(char[][] myArray){
for(int i = 0; i < myArray.length; i++){
for(int j = 0; j < myArray.length; j++){
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
queryNum += 1;
}
}
}
System.out.println(queryNum);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
//Create an alphabet array so I can use this to fill in the searchBox array
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
System.out.println("Please choose an array size: ");
int a = keyboard.nextInt();
//Create a square array
char[][] searchBox = new char[a][a];
//Fill in the array with random chars
for(int i = 0; i < searchBox.length; i++){
for(int j = 0; j < searchBox[i].length; j++){
int randNum = random.nextInt(25);
searchBox[i][j] = alphabet[randNum];
}
}
//Implement my method to print the array to the screen
System.out.println("Here is the square matrix with random letters: ");
printArray(searchBox);
System.out.println("Enter a query to search: ");
searchArray(searchBox);
}
}
This will print out my array but I can't seem to get the search to work.
Modified Your searchArray function
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
String out = null;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
//System.out.println(i+":"+j+a[i][j]);
//w+=1;
if(out==null)
{
out=String.valueOf(a[i][j]);
}else
out=out+a[i][j];
for(int f = 1; f < query.length(); f++){
if(j+f<5){
if(a[i][j+f] == query.charAt(w+f)){
// System.out.println(i+"Index:w+f"+w+f+query.charAt(w+f)+"query.charAt(w+f)Index"+query.indexOf(query.charAt(w+f)));
// System.out.println(i+":"+j+a[i][j+f]);
out=out+a[i][j+f];
System.out.println(out+":"+query+"here"+out.length()+query.length());
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
}
}
} if(out!=null)
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
out=null;
}
}
}
System.out.println(queryNum);
}
OuptPut

Categories