Extras values after calling main method - java

This program works fine if i enter the correct value (int value). However, when I enter in a character or any other wrong value it displays the wrong input message and calls the main method again. The only problem is after calling the main method and inputting the correct input it prints out extra data why is that?
import javax.swing.JOptionPane;
public class TestPolyVal {
public static void main(String[] args){
int xValue = 0;
String value = JOptionPane.showInputDialog(null, "What is the value of X");
try{
xValue = Integer.parseInt(value);}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
TestPolyVal.main(args);
}
int[] intArray = new int[20] ;
for (int i = 0; i < 20; i ++){
intArray[i] = 2;}
System.out.println(calculateBruteForce(intArray,xValue));
System.out.println("0");
System.out.println(calculateHorner(intArray,xValue));}
static int calculateBruteForce(int[] a, int b){
int sum = 0 ;
for (int i = 0; i < 20; i ++){
sum +=a[i]*powerCalc(b,i);}
return sum;}
static int powerCalc(int c, int d){
int powerValue = c;
if (d==0){
powerValue = 1;}
else if (d==1){
powerValue = c;}
else if (d>1){
for (int i = 1; i<d;i++){
powerValue = powerValue*c;}}
return powerValue;}
static int calculateHorner(int[] e, int f){
int acc = e[e.length-1];
for(int i = e.length-2; i >= 0; i--){
acc = (acc * f)+ e[i];}
return acc;}
}

You are getting extra printouts because the first main execution will continue after the second main invocation is done.
This can be fixed by adding a return; after the new call to main:
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
TestPolyVal.main(args);
return;
}

The approach of calling main() from within main() is not a great approach in this case. I, as an adversarial user, could just type 'a' in the dialog over and over again. Eventually this would cause a Stack Overflow Error and your program would crash.
I would suggest using a loop.
while(true) {
try{
xValue = Integer.parseInt(value);
break;
}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null,"Wrong input. Please input only integer values.");
}
}
This way your program would just loop forever or until the user enters correct input instead of crashing. Unless you're implementing a recursive algorithm, I can't think of any reason for a method to invoke itself.

Related

why isn't the rest of my method being called? (loop being ignored)

i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();

Program doesn't step into method

I am trying to figure out why my program doesn't seem to be stepping into one of my methods: assignKennel(). Instead, it keeps asking for more input, even though theres more to do in the while loop. Any advice will be much appreciated. I'm not sure what to include, so here is all I have.
package finalbarking;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Finalbarking {
//global int numberOfDogs, numberOfKennels;
static int numberOfDogs, numberOfKennels=8;
//int dogID
static int [] dogIDs= new int [15];
//add provided ID's
//String dogNames
static String [] dogNames= new String [15];
//add provided dogs to array
//int dogWeights
static int [] dogWeights= new int [15];
//add provided weights to array
//at start, this is empty.
//array size = 8 elements myArray = new int[7]
//int KennelNumber
static int [] kennelNumbers= new int [8];
//String kennelWeight(SMALL / MEDIUM / LARGE)
static String [] kennelWeight= new String [3];
//int dogInKennelID
static int [] dogInKennelID= new int [8];
static int inputDogID=0;
public static void main(String[] args) throws InterruptedException {
//vars
//Scanner
Scanner response= new Scanner(System.in);
//int inputDogID
dogIDs[0]=1001;
dogIDs[1]=1003;
dogIDs[2]=1007;
dogIDs[3]=1008;
dogIDs[4]=1012;
dogIDs[5]=1034;
dogIDs[6]=1038;
dogIDs[7]=1087;
dogIDs[8]=1088;
dogIDs[9]=1120;
dogIDs[10]=1129;
dogIDs[11]=1145;
dogIDs[12]=1200;
dogIDs[13]=1211;
dogIDs[14]=1222;
dogNames[0]= "Bowser";
dogNames[1]= "Ginger";
dogNames[2]= "Molly";
dogNames[3]= "Murphy";
dogNames[4]= "Roxy";
dogNames[5]= "Samantha";
dogNames[6]= "Duke";
dogNames[7]= "Pookie";
dogNames[8]= "Abby";
dogNames[9]= "Barney";
dogNames[10]= "Autumn";
dogNames[11]= "Hershey";
dogNames[12]= "King";
dogNames[13]= "Bosco";
dogNames[14]= "Daisy";
dogWeights[0]=130;
dogWeights[1]=80;
dogWeights[2]=45;
dogWeights[3]=18;
dogWeights[4]=70;
dogWeights[5]=12;
dogWeights[6]=90;
dogWeights[7]=16;
dogWeights[8]=35;
dogWeights[9]=65;
dogWeights[10]=20;
dogWeights[11]=100;
dogWeights[12]=110;
dogWeights[13]=70;
dogWeights[14]=55;
kennelWeight[0] = "SMALL";
kennelWeight[1] = "MEDIUM";
kennelWeight[2]= "LARGE";
//reset at end
//Greeting for employee
System.out.println("Hello Barking Lot Employee!");
//begin loop
while(inputDogID!=9999){
//try
try{
//prompt for dog id, 9999 as sentinel value
System.out.println("Please enter the dog's ID number, or '9999' to quit)");
//capture
inputDogID= response.nextInt();
//end try start catch exception
}catch(InputMismatchException error){
//Invalid
System.err.println("You've entered an invalid Dog ID. Try again(Please refer to our Dog Client List, they are all 4 digits long).");
//pause program
Thread.sleep(10);
//reset scanner
response = new Scanner(System.in);
}//end catch
int foundDogID = 0;
for(int count=0; count<15; count++)
{
if(dogIDs[count] == inputDogID){
foundDogID = count;
}//end if
}//end for
currentClients(dogIDs,dogNames,dogWeights,inputDogID);
//assignKennel()
assignKennel(foundDogID);
//displayKennel();
displayKennel();
}//endwhile
}//end main
//User Defined Methods
//CurrentClients- Identifies dog based on list of current clients
public static void currentClients(int[]dogIDs,String[]dogNames,int[]dogWeights,int inputDogID){
//Takes 3 arrays(ID, NAME, WEIGHT)
//Takes inputDogID
//Iterate the array and check if inputDogID == ID[count]
//for(int count = 0; count < numberOfDogs; count++)
for(int count = 0; count <= numberOfDogs; count ++){
//if(inputDogID == ID) then return NAME + WEIGHT;
if(inputDogID==dogIDs[count]){
System.out.println("Dog Name : "+dogNames[count]+"\tDog Weight: "+ dogWeights[count]);
}//end if
//else then return 0 and display an error
else
System.out.println("Did not find a dog matching this ID Number.");
}//end for
}//endCurrentClients
//assignKennel-assigns dogs to kennels
public static void assignKennel(int dogIDs){
//takes 1 int dogID
//Iterate the array and check:
//var
boolean didDogGetKennel=false;
for(int count = 0; count < numberOfKennels; count++){
//if(getDogWeightClass(dogWeights[dogID]).equals(kennelWeight[count]))
String weightClass = getDogWeightClass(dogWeights[dogIDs]);
for(int counter = 0; counter < 3; counter++)
{
if(weightClass.equals(kennelWeight[counter]))
{
if(dogInKennelID[count] == 0){
//then EMPTY, assign
didDogGetKennel=true;
dogInKennelID[count]=dogIDs;
}//end if
}
}
}//end for loop
//if didDogGetKennel=false display message: "I'm sorry all ken
if(didDogGetKennel==false)
System.out.println("I'm sorry, all of our kennels for that weight limit are filled.");
}//end assignKennel
//displayKennel- displays the eight kennel numbers &the dog assigned to each
public static void displayKennel(){
// print if all kennels are filled
if(areKennelsFull()){
for(int count =0; count<=8; count ++)
System.out.println(kennelNumbers[count] + getDogName(dogInKennelID[count]));
}//end if
//else if print if sentinel value is enter
else if(inputDogID==9999){
for(int count =0; count<=8; count ++)
System.out.println(kennelNumbers[count] + getDogName(dogInKennelID[count]));
}//end else if
}//end displayKennel
//getDogWeightClass()
public static String getDogWeightClass(int dogWeight){
//take int dog weight
//if dog weight < 50, then SMALL
if(dogWeight<50)
return "SMALL";
//else if dog weight >50 &&<100 then MEDIUM
else if(dogWeight>50 &&dogWeight <100)
return "MEDIUM";
//else then LARGE
else
return "LARGE";
//return String S/M/L
}//end getDogWeightClass
//getDogName()
public static String getDogName(int dogInKennelID){
//take dogInKennelID
return dogNames[dogInKennelID];
}//end getDogName
//areKennelsFull()
public static Boolean areKennelsFull(){
for(int count =0; count<=8; count ++){
if (dogInKennelID[count] ==0)
return false;
//return boolean false
//else return boolean true
else
return true;
}//end for
return false;
}//end areKennelsFull
}//end class
It actually does run assignKennel(). If you put a System.out.println() statement in there to verify that that method runs, you'll see that it does. The problem isn't with that method; every method is running as it should.
Your problem is in displayKennel(). It isn't doing anything. areKennelsFull() evaluates to false, as does inputDogID==9999 (assuming some other id was typed in). I'm guessing areKennelsFull() is supposed to evaluate to true after a valid ID has been entered, so the root cause of this problem is most likely either in areKennelsFull() or perhaps in assignKennels() incorrectly assigning a value somewhere in dogInKennelID.
It does enter that routine, but one problem I see is that you are exceeding the array index. You have the condition "count<=8" in 3 for statements which should read "count<8" (remove the "="). When it tries to use index 8, it bombs, and so the program cannot finish properly. The array is indexed from 0 to 7, so 8 is invalid.

do the cross-sum correctly

So im trying to do cross-sums: 321=6 because 3+2+1=6 however ive run into a problem that i can locate with my code and was hoping if anyone else could help me to locate it
import java.util.*;
public class Thewierdo {
public static void main(String[] args) {
Scanner Tinput = new Scanner (System.in);
System.out.print("input number for cross-sum examination: ");
Double Tin = Tinput.nextDouble();
int m = 0;
if (Tin.isNaN()){
System.out.print("actual whole number please: ");
Tin = Tinput.nextDouble();
}else{
int cool = Tin.intValue();
String gotcha= String.valueOf(cool);
int heads = gotcha.length();
while(heads >= 0){
System.out.println(gotcha.charAt(1));
char Tails=gotcha.charAt(heads);
int finald = Character.getNumericValue(Tails);
heads=heads-1;
m += finald;
//made by Christian Risom
}
System.out.print(m);
}
}
}
That's my solution, i'm sure you could make it more simple, but there you go:
public static int cross_sums(int input) {
int output = 0;
do {
output += input % 10;
input /= 10;
} while (input > 0);
if (output > 9) {
output = cross_sums(output);
}
return output;
}
The way you are checking if it is a valid number doesn't work. An error will be thrown on Tinput.nextDouble() if the input can't be interpreted as a double.
As others are saying, read your errors and debug. You likely have other problems as well.

How to back up a line after a new line submitted by a user? Java

Suppose, you ask user to provide you some input via a console app in Java. They do and hit Enter. You get the string and do something in response. Say, you calculate some value based on the user's input and print it out.
How might I print out a response on the same line as user's input? I'd like to (possibly) delete a new line character and print out a response next to his input.
Please advise how to do this using Java.
Thank you.
You cannot control the Console through basic Java.I think you can use JLine to control the Console.In java 6 u have java.io.Console class through which you can echo asterisk *'s when password has to be read.
http://blogs.oracle.com/alanb/entry/java_io_console_is_finally
I have tried to implement this with the help of jcurses library and here is a demo of something you are looking for
import jcurses.system.CharColor;
import jcurses.system.InputChar;
import jcurses.system.Toolkit;
public class TestClass {
public static void main(String[] args) {
try {
CharColor printColor = new CharColor(CharColor.BLACK, CharColor.WHITE);
int i = 0;
int j = 0;
while (true) {
StringBuilder str = new StringBuilder();
InputChar c = null;
do {
c = Toolkit.readCharacter(); //Read each character
if (c.getCharacter() != 10) { //Do not print character if Return key
str.append(c);
Toolkit.printString(String.valueOf(c), i++, j, printColor); //Print character as you type
}
} while (c.getCharacter() != 10);
Toolkit.printString(processInput(str.toString()), i, j++, printColor);
i = 0;
if (j == Toolkit.getScreenHeight()) {
Toolkit.clearScreen(printColor);
j = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String processInput(String input) {
return " Input processed";
}
}
You can with ANSI-Codes. In Linux I never had a problem to use them, but on Windows, you have to install ANSI.SYS first.
import java.util.Random;
public class AnsiMove
{
public AnsiMove ()
{
Random random = new Random ();
System.out.print ("ESC[2J");
for (int i = 0; i < 10000; ++i)
{
int y = random.nextInt (23) + 1;
int x = random.nextInt (79) + 1;
char c = (char) (random.nextInt (95) + 32);
gotoXY (x, y);
System.out.print (c);
pause (1);
}
}
void pause (int p)
{
try
{
Thread.sleep (p);
}
catch (InterruptedException e)
{
System.err.println (e);
}
}
void gotoXY (int x, int y)
{
System.out.print ("ESC[" + y + ';' + x + 'H');
}
/** */
public static void main (String args[])
{
new AnsiMove ();
}
}

Uva's 3n+1 problem

I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}

Categories

Resources