I was writing some code for an interviewstreet.com challenge
My code gives a NumberFormatException
import java.io.*;
public class BlindPassenger
{
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int t,n;
//System.out.println(line);
t = Integer.parseInt(line);
for(int i=0;i<t;++i)
{
line = br.readLine();
n = Integer.parseInt(line); --n;
if(n == 0)
{
System.out.println("poor conductor");
}
else
{
char direction='l',seat_posn='l';
int row_no = 0, relative_seat_no = 0;
row_no = (int) Math.ceil(n/5.0);
relative_seat_no = n % 5;
if(row_no % 2 == 0)
{
//even row, need to reverse the relative seat no
relative_seat_no = 6 - relative_seat_no;
}
if(relative_seat_no < 3)
{
direction = 'L';
if(relative_seat_no == 1) seat_posn = 'W';
else seat_posn = 'A';
}
else
{
direction = 'R';
if(relative_seat_no == 3) seat_posn = 'A';
else if(relative_seat_no == 4) seat_posn = 'M';
else seat_posn = 'W';
}
System.out.println(row_no + " " + seat_posn + " " + direction);
}
}
}
}
Here is the test case that they use
3
1
2
3
Output:
poor conductor
1 W L
1 A L
There seems to be a trailing space or something at the end of each line that causes the exception.
$ java BlindPassenger <input00.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: "3
"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at BlindPassenger.main(BlindPassenger.java:11)
This has taken up half an hour and I don't know how to fix this.
Kills the fun of the event doesn't it. Can someone tell me what I'm doing wrong.
Integer.parseInt() can't handle strings that don't fit its expected format, as you've found out. You could trim() the string before you parse it:
t = Integer.parseInt(line.trim());
This gets rid of leading and trailing whitespace.
You have to trim the string
import java.io.*;
public class BlindPassenger
{
public static boolean isEmpty(final String string)
{
return string == null || string.trim().isEmpty();
}
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int t,n=0;
//System.out.println(line);
t = Integer.parseInt(line);
for(int i=0;i<t;++i)
{
line = br.readLine();
if(!isEmpty(line)){
n = Integer.parseInt(line.trim());
--n;
}
if(n == 0)
{
System.out.println("poor conductor");
}
else
{
char direction='l',seat_posn='l';
int row_no = 0, relative_seat_no = 0;
row_no = (int) Math.ceil(n/5.0);
relative_seat_no = n % 5;
if(row_no % 2 == 0)
{
//even row, need to reverse the relative seat no
relative_seat_no = 6 - relative_seat_no;
}
if(relative_seat_no < 3)
{
direction = 'L';
if(relative_seat_no == 1) seat_posn = 'W';
else seat_posn = 'A';
}
else
{
direction = 'R';
if(relative_seat_no == 3) seat_posn = 'A';
else if(relative_seat_no == 4) seat_posn = 'M';
else seat_posn = 'W';
}
System.out.println(row_no + " " + seat_posn + " " + direction);
}
}
}
}
Related
This was one of coding jam 2020 questions with the link attached below (round is complete), and while I could not reproduce it, the google engine reported that this was a runtime error even for the small test case. It could pretty much handle any test case I threw at it. Perhaps I am missing an edge case, but not sure what it is.
My understanding is that this is O(N) performance. All it really does is to check if the boolean sub array is free(false) and if so, assign the task to that sub array(true) with may be 2N compares.
https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020bdf9
import java.util.*;
import java.io.*;
//Parenting Partnering Returns
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc.
for (int ijk = 1; ijk <= t; ++ijk) {
int N = in.nextInt();
String ans;
StringBuilder sb = new StringBuilder();
boolean[] cal = new boolean[1442];
boolean[] jal = new boolean[1442];
int si, se;
boolean canC,canJ, isPossible = true;
for (int i = 0 ; i < N ; i++) {
si = in.nextInt();
se = in.nextInt();
canC = false; canJ = false;
if (cal[si + 1] == false && cal[se] == false || cal[si] == false && cal[se -1] == false) {
for (int j = si ; j <= se; j++) cal[j] = true;
sb.append('C'); canC = true; continue;
} else if (jal[si + 1] == false && jal[se] == false || jal[si] == false && jal[se -1] == false) {
for (int k = si ; k <= se; k++) jal[k] = true;
sb.append('J'); canJ = true; continue;
} else {
isPossible = false;
break;
}
}
ans = sb.toString();
if(isPossible)
System.out.println("Case #" + ijk + ": " + ans);
else System.out.println("Case #" + ijk + ": " + "IMPOSSIBLE");
}
//in.close();
}
}
Using java, input string="aabbcdeaaaabbb" and the output must be aaaa, as sequence here is having repeated 4 times a. Can anyone help me to get this "aaaa" as output using java implementation.
Algorithm to find the Longest substring having same character repeated.
for eg:
I/P: aabbcdefaaaacccccc O/P: cccccc
Please check my program below and suggest any optimization for faster processing:
public class LongestSubString {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter a word to find longest substring with same characters repeated");
String word = reader.readLine();
System.out.println("Entered word is: " + word);
System.out.println("Longest repeated characters substring is: "
+ subStringFinder(word));
}
/*
*longest substring finder with same character repeated
*/
public static String subStringFinder(String word) {
char[] tokens = word.toCharArray();
int len = tokens.length;
int wordLen = word.length();
System.out.println("len of input word: " + wordLen);
List<String> myList = new ArrayList<>();
StringBuilder strConcat = new StringBuilder("");
for (int j = 0; j <= len - 1; j++) {
if (j + 1 > len - 1) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
}
}
else {
if (tokens[j] == tokens[j + 1]) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
} else {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
}
}
}
int max = 0, index = 0;
for (int i = 0; i < myList.size(); i++) {
String strEle = myList.get(i);
int strLen = strEle.length();
if (max < strLen) {
max = strLen;
index = i;
}
}
return myList.get(index);
}
}
I believe your code is overly complicated. You don’t need a StringBuilder nor an ArrayList. I tried to understand your intention, but then skipped it and wrote my own version instead. Hope it helps anyway.
public static String subStringFinder(String word) {
if (word == null || word.isEmpty()) {
return word;
}
char currentChar = word.charAt(0);
int longestStart = 0;
int longestLength = 0;
int currentStart = 0;
int currentLength = 1;
for (int ix = 1; ix < word.length(); ix++) {
if (word.charAt(ix) == currentChar) {
currentLength++;
} else {
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
currentChar = word.charAt(ix);
currentStart = ix;
currentLength = 1;
}
}
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
return word.substring(longestStart, longestStart + longestLength);
}
String in = "aabbcdeaaaabbb";
String t;
ArrayList<String> out = new ArrayList<String>();
String l="";
int c=0;
String n;
for(int i=0;i<in.length;i++) {
n=in.substring(i, i+1); //get the current character
if(n.equals(l)){
l=n; c++;
}
else {
t=n;
for(int j=1;j<c;j++) {
n+=t;
}
c=0;
out.add(n);
c=0;
}
}
I am a student (big time "Newbie") learning java. The two examples below are in fact homework. Example 1 is a game of guess the card (black or red) and Example 2 is a game of rock, paper ,scissors.
I have searched this site for answers, and the responses I have seen go out of context with where we are in our curiculum. At this point we are in do/while, while & for loops.
This is the code I came up with (no small feat for me) that I would like to have debuged. I do not care about making it more efficient or anything of the like. I am more concerned with having it work. I am using netbeans and I have put (<---)'s where there seems to be a problem. Your help would be greatly appriciated. Thanks in advance.
P.S. The course is in french, so do not be suprised if some of the variable names do not make sense.
EX1------------------------------------------------------------------------------------
package devoir.pkg3;
import java.util.Scanner;
public class Dev3Ex4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char r = 'r', n = 'n', q = 'q';
int i, compteur = 0, compteurDeux = 0;
do {
System.out.println("Deviner la couleur de la carte. \"r\" rouge, \"n\" noire et \"q\" quitter.");
char clavier = scanner.next().charAt(0);
i = (int) (2.0 * Math.random());
compteur = compteur + 1;
if (i == 0) {
char tmp = 'n';
}
if (i == 1) {
char tmp = 'r';
}
if (clavier == tmp) { <------ (temp value error)
compteurDeux = compteurDeux + 1;
System.out.println("Bon choix ! Score: " + compteurDeux + "/" + compteur);
}
if (clavier != tmp) { <------ (temp value error)
System.out.println("Non...Score: " + compteurDeux + "/" + compteur);
}
} while (clavier != 'q'); <------ (clavier value error)
System.out.println("Votre score final est " + compteurDeux + "/" + compteur);
}
}
EX2------------------------------------------------------------------------------------
package devoir.pkg3;
import java.util.Scanner;
public class Dev3Ex5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char q = 'q';
int i, compteur = 0, compteurDeux = 0;
do {
System.out.println("Jouons a Roche/papier/ciseaux. \"r\" roche, \"p\" papier. \"c\" ciseax et \"q\" quitter.");
char clavier = scanner.next().charAt(0);
i = (int) (3.0 * Math.random());
if (clavier == 'r') {
int tmp = 0;
}
if (clavier == 'c') {
int tmp = 1;
}
if (clavier == 'p') {
int tmp = 2;
}
if (tmp == 0 && i == 1 || tmp == 1 && i == 2 || tmp == 2 && i == 0) {<--(All tmp values error)
compteur = compteur + 1;
System.out.println("Bon choix ! Score: " + compteur + "/" + compteurDeux);
}
if (tmp == 1 && i == 0 || tmp == 2 && i == 1 || tmp == 0 && i == 2) {<--(All tmp values error)
compteurDeux = compteurDeux + 1;
System.out.println("Non...Score: " + compteur + "/" + compteurDeux);
}
if (tmp == i) { <--(tmp value error)
System.out.println("Parti nul. Score " + compteur + "/" + compteurDeux);
}
} while (clavier != 'q'); <--(clavier value error)
System.out.println("Votre score final est " + compteur + "/" + compteurDeux);
}
}
You have problems with your local variable declaration inside code blocks
if (i == 0) {
char tmp = 'n';
}
if (i == 1) {
char tmp = 'r';
}
Change it to something like this:
char tmp='';
if (i == 0) {
tmp = 'n';
}
if (i == 1) {
tmp = 'r';
}
Same for char clavier and int tmp - declare & define them first before using them, usually at the start of your function, so that all your variables will be in one place.
Note: This is considered to be best practice to define variables at the top of your Method and class block.
Your issue is one of scope: when you define char tmp = 'n' inside of an if { } block, that variable tmp is available for use only inside of that block. You need to define char tmp outside of the series of if statements, then simply specify its value inside them, like:
char tmp = ' ';
if (i == 0) {
tmp = 'n';
}
else if (i == 1) {
tmp = 'r';
}
etc.
Same thing for your clavier variable in both examples, which are declared inside the do {} block, and will thus be available only inside that block, not in the control for the block.
1.char tmp has to be declared outside the block as shown below.
char tmp;
if (i == 0) {
tmp = 'n';
}
if (i == 1) {
tmp = 'r';
}
Same with clavier, has to be declared outside do to be used in the while condition.
char clavier
do{
2.Same with the second program. declare the tmp values outside and then use them.
This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
When I do different combinations like d-c+a+b it gives me a inccorect number like 118.0. Can someone tell me where in my code my calculations are wrong..
Thank you
the ValVarPairs.txt contains these numbers-> a=100,b=5,c=10,d=13
This is what i coded.
package com.ecsgrid;
import java.io.*;
public class testC {
public static void main(String[] args) {
int i = 0,j = 0;
double result, values[] = new double[4];
char k, operators[] = new char[3];
for (i = 0; i <= 2; i++)
operators[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)){
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
}
catch(FileNotFoundException e) { System.err.println(e); return; }
catch(IOException f) { System.out.println(f); return; }
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine();
}
catch(IOException f) { System.out.println(f); return; }
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
result = values[0];
for (i = 0; i <= 2; i++){
if (operators[i] == '+')
result = result + values[i+1];
else
result = result - values[i+1];
}
System.out.println(result);
}
}
Right now you would be getting the same output if your input was -++
You never parse for the order or a, b, c and d. You always assume the order a->b->c->d.
So d-c+a+b will be: a-b+c+d which is consistent with the output you provided(100-5+10+13 = 118)
OP's CODE
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
/OP'S CODE
In this loop, when k is not an operator, you should be reading which letter it is, and store the order in which the letters appeared. Or build some other kind of mapping. In any case you can't just ignore non-operator characters because they are part of the input.
Let's debug this a little, add a few system outs...
this is what you would see for each step
100.0 - 5.0
95.0 + 10.0
105.0 + 13.0
118.0
your value array is {100,5,10,13} and your operator array is {-,+,+}
you have not mapped a = 100, b = 5, c= 10, d = 13, unless you map those then parse the operands using the mapping based on the non operand input keys, it is not going to work.
So, if I were to use the character's int values, I would be able to translate it this way.
import java.io.*;
public class TestC {
public static void main(String[] args) {
int i = 0, j = 0;
double result, values[] = new double[4];
char k, operatorsAndOperands[] = new char[3];
for (i = 0; i <= 2; i++)
operatorsAndOperands[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)) {
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
for (int l = 0; l < values.length; l++) {
System.out.println(values[l]);
}
} catch (FileNotFoundException e) {
System.err.println(e);
return;
} catch (IOException f) {
System.out.println(f);
return;
}
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine().toUpperCase();
} catch (IOException f) {
System.out.println(f);
return;
}
if(InputText.length() > 0){
operatorsAndOperands = new char[InputText.length()];
} else {
System.out.println("No Operations specified");
return;
}
for (i = 0; i < InputText.length(); i++) {
k = InputText.charAt(i);
operatorsAndOperands[j++] = k;
}
result = 0;
for (i = 0; i < operatorsAndOperands.length; i++) {
System.out.println(operatorsAndOperands[i] + " " + (int)operatorsAndOperands[i]);
if(i+1<operatorsAndOperands.length)
System.out.println(operatorsAndOperands[i+1]);
switch(operatorsAndOperands[i]){
case '+':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result+=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
case '-':
if(operatorsAndOperands[i+1] != '+' && operatorsAndOperands[i+1] != '-'){
result-=values[(int)operatorsAndOperands[i+1] - (int)'A'];
i++;
}
break;
default:
result = values[(int)operatorsAndOperands[i] - (int)'A'];
break;
};
System.out.println(result);
}
System.out.println(result);
}
}
I am trying to get user input for sortValues[] array using the for statement (enter character 1, enter character 2, etc).
However, when I execute this, the program will not allow me to enter for character 2, instead skipping directly to character 3, as seen below.
How to resolve this? The code is included below.
thanks!
static public void s_1d_char () {
int counter=0;
int x=0;
c.print("How many characters? ");
counter = readInt();
char[] sortValues = new char[counter+1];
for (x=1;x<=counter;x++) {
System.out.println("Enter character "+(x)+":");
sortValues[x] = readChar();
}
}
readChar implementation (this is from a library):
public synchronized char readChar ()
{
char result, ch;
if (ungotChar != EMPTY_BUFFER)
{
result = (char) ungotChar;
ungotChar = EMPTY_BUFFER;
return (result);
}
if (lineBufferHead != lineBufferTail)
{
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
return (result);
}
startRow = currentRow;
startCol = currentCol;
if (currentRow > maxRow)
{
startRow++;
currentCol = 1;
}
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (true);
// Wait for a character to be entered
while (true)
{
ch = getChar ();
if (ch == '\n')
{
clearToEOL = false;
if (echoOn)
print ("\n");
clearToEOL = true;
lineBuffer [lineBufferHead] = '\n';
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
break;
}
if (ch == '\b')
{
if (lineBufferHead == lineBufferTail)
{
consoleCanvas.invertScreen ();
}
else
{
int chToErase;
lineBufferHead = (lineBufferHead + lineBuffer.length - 1) % lineBuffer.length;
chToErase = lineBuffer [lineBufferHead];
if (echoOn)
{
if (chToErase != '\t')
{
erasePreviousChar ();
}
else
{
int cnt;
eraseLineOfInput ();
cnt = lineBufferTail;
while (cnt != lineBufferHead)
{
print (lineBuffer [cnt]);
cnt = (cnt + 1) % lineBuffer.length;
}
}
}
}
} // if backspace
else if (ch == '\025')
{
if (echoOn)
{
eraseLineOfInput ();
}
lineBufferHead = lineBufferTail;
}
else
{
if (echoOn)
{
print (ch);
}
lineBuffer [lineBufferHead] = ch;
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
}
} // while
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (false);
return (result);
}
I recommend getting user input with a scanner:
import java.util.Scanner;
// ...
int counter = 0;
System.out.println("How many characters?");
Scanner keyboard = new Scanner(System.in);
counter = keyboard.nextInt();
char[] sortValues = new char[counter+1];
// Start your index variable off at 0
for (int x = 0; x < counter; x++) {
System.out.println("Enter character "+(x)+":");
keyboard = new Scanner(System.in);
String line = keyboard.nextLine();
sortValues[x] = line.charAt(0);
}
This will capture the first character of the line. If the user enters more than one character, the program will read only the first.
Also, you should really start your index variable x off at 0, considering arrays are 0-based indexed.
instead of readChar() try:
sortValues[x] = Integer.parseInt(System.console().readLine());
How to read integer value from the standard input in Java