I am working on a problem where I have a menu option 1. to shuffle the word, 2 to take the shuffle word and try to fix it by changing the array index numbers.
I did this part if (input==1) shuffle the word.
I now have to take that the same shuffle word in in if (input==2) section and try to fix it. Can anybody guide me how can I use the same values in this block if(input==1)?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
while (true) {
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
String team;
String mix_word;
char orig_team[];
char mix_team[];
boolean Result;
// System.out.println(input);
if (input == 1) {
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
int arg_length = mix_team.length;
}
if (input == 2) {
}
if (input == 3) {
break;
}
if (input > 3 || input <= 0) {
System.out.println("input accurate numbers 1 or 2 or 3");
}
}
}
static String mix(String Team) {
String word = shuffle(Team);
return word;
}
static String shuffle(String input) {
List<Character> characters = new ArrayList<Character>();
for (char c : input.toCharArray()) {
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while (characters.size() != 0) {
int randPicker = (int) (Math.random() * characters.size());
output.append(characters.remove(randPicker));
}
return output.toString();
}
static String orig()
{
String[] lines = new String[1000];// Enough lines.
int counter = 0;
try {
File file = new File("input.txt");// The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag = true;
while (true) {
try {
lines[counter] = buffer.readLine();// Store a line in the
// array.
if (lines[counter] == null) {// If there isn't any more
// lines.
buffer.close();
fileReader1.close();
break;// Stop reading and close the readers.
}
counter++;
} catch (Exception ex) {
break;
}
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter) + 0;
return (lines[pick]);
}
}
In every loop cycle (which handles a single user input) you declare your variables, so their scope (the access range) is limited to that cycle.
If you declare your variables outside the while-loop, their scope will stretch over the whole loop (until the end of the method):
public static void main(String[] args) {
String team = "";
String mix_word = "";
char orig_team[] = null;
char mix_team[] = null;
boolean Result = false;
while (true) {
// ** your usual input handling here **
}
}
Also be sure to initialize them (e.g. with a default value), or else the program will not compile.
Another way would be to create member- or class-variables, which would have the advantage of automatic initialization and a larger scope.
This is a rather pathological use case of the switch statement but you can take advantage of the drop-through and do the following:
switch(input) {
case 1:
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
arg_length = mix_team.length;
// No break; here!
case 2:
// do the rest of your thing as if it were case 2
break;
case 3:
break;
default:
System.out.println("input accurate numbers 1 or 2 or 3");
}
Related
This is my code. I want to read a file called "write.txt" and then once it reads. Compare it with a word, here I use "target variable(of string type) once the comparison is done inside the method called findTarget it will return 1 after the condition is true. I try to call the method but I keep getting an error. test.java:88: error: cannot find symbol
String testing = findTarget(target1, source1);
^
symbol: variable target1
location: class test
1 error
can someone correct my mistake. I am quite new to programming.
import java.util.*;
import java.io.*;
public class test {
public static int findTarget( String target, String source )
{
int target_len = target.length();
int source_len = source.length();
int add = 0;
for(int i = 0;i < source_len; ++i) // i is an varialbe used to count upto
source_len.
{
int j = 0; // take another variable to count loops
while(add == 0)
{
if( j >= target_len ) // count upto target length
{
break;
}
else if( target.charAt( j ) != source.charAt( i + j ) )
{
break;
}
else
{
++j;
if( j == target_len )
{
add++; // this will return 1: true
}
}
}
}
return add;
//System.out.println(""+add);
}
public static void main ( String ... args )
{
//String target = "for";
// function 1
try
{
// read the file
File file = new File("write.txt"); //establising a file object
BufferedReader br = new BufferedReader(new FileReader(file));
//reading the files from the file object "file"
String target1;
while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
System.out.println(target1);
//target.close();
}
catch (IOException e)
{
System.out.println("file error!");
}
String source1 = "Searching for a string within a string the hard way.";
// function 2
test ob = new test();
String testing = findTarget(target1, source1);
// end
//System.out.println(findTarget(target, source));
System.out.println("the answer is: "+testing);
}
}
The error is because findTarget is a class function.
So, where you have this:
test ob = new test();
String testing = findTarget(target1, source1);
...should be changed to call the function from a static context:
//test ob = new test(); not needed, the function is static
int testing = test.findTarget(target1, source1);
// also changed the testing type from String to int, as int IS findTarget's return type.
I don't have your file contents to give a trial run, but that should at least help get past the error.
=====
UPDATE:
You are close!
Inside main, change the code at your loop so that it looks like this:
String target1;
int testing = 0; // move and initialize testing here
while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
{
//System.out.println(target1);
testing += test.findTarget(target1, source1);
//target1 = br.readLine();
}
System.out.println("answer is: "+testing);
I have finally been able to solve my problem. but extending the functionalities. I want to increment the add by 1. but in my programming, it keeps giving me output as
answer is: 1 answer is: 1
instead I want my program to print not two 1's rather 1+1 = 2
can someone fix this incrementing problem?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class test {
public static int findTarget(String target, String source) {
int target_len = target.length();
int source_len = source.length();
int add = 0;
// this function checks the character whether it is present.
for (int i = 0; i < source_len; ++i) // i is a varialbe used to count upto source_len.
{
int j = 0; // take another variable to count loops
while (add == 0)
{
if (j >= target_len) // count upto target length
{
break;
}
else if (target.charAt(j) != source.charAt(i + j))
{
break;
}
else
{
++j;
if (j == target_len)
{
add++; // this will return 1: true
}
}
}
}
return add;
//System.out.println(""+add);
}
public static void main(String... args) {
//String target = "for";
// function 1
try {
// read the file
Scanner sc = new Scanner(System.in);
System.out.println("Enter your review: ");
String source1 = sc.nextLine();
//String source1 = "Searching for a string within a string the hard way.";
File file = new File("write.txt"); //establising a file object
BufferedReader br = new BufferedReader(new FileReader(file)); //reading the files from the file object "file"
String target1;
while ((target1 = br.readLine()) != null) //as long the condition is not null it will keep printing.
{
//System.out.println(target1);
int testing = test.findTarget(target1, source1);
System.out.println("answer is: "+testing);
//target1 = br.readLine();
}
br.close();
}
catch (IOException e)
{
System.out.println("file error!");
}
}
}
I have a file called "results.txt" which has these values inside:
0118210:1801:XDCS1094:A:4
0118210:1801:XDCS2034:B+:4
0118210:1801:XDCS1043:C:3
0118024:1801:XDCS1094:B:4
0118024:1801:XDCS2094:A:4
I want to read the file, make it an array and remove the delimiter and calculate based on the GPA formula. This is my thought of how it should work, but I'm still not so sure because I'm new to programming. I am also trying to display my results on a new line instead of everything in a single line as shown in the image. Any help would be appreciated, it is an assignment.
public void run()
{
try{
do{
found=0;
received = in.readLine();
array2=received.split(":");
if(received.equals("QUIT")) break;
switch(received.charAt(0))
{
case 'R':
Register();
break;
case 'L':
login();
break;
case 'V':
View();
break;
}
}while(!received.equals("QUIT"));
}
catch(IOException e)
{
e.printStackTrace();
}
public void View() throws IOException
{
String grade ="";
in3 = new BufferedReader(new FileReader("results.txt"));
while((result = in3.readLine()) !=null)
{
array4=result.split(":");
if((array2[1].equals(array4[0])) && (array2[2].equals(array4[1])))
{
grade += array4[2]+" "+array4[3]+" "+array4[4];
found=1;
}
if(found==0)
out.println("No Records");
}
out.println(grade);
GCPA();
}
public void CGPA() throws IOException{
String grade = "", cgpa = "";
int IntValue = 0, IntCH = 0, IntCGPA = 0, IntArray = 0;
if(array4[3] == "A") {
IntArray = Integer.parseInt(array4[3]);
IntValue = IntArray * 4;
} else if(array4[3] == "B") {
IntArray = Integer.parseInt(array4[3]);
IntValue = IntArray * 3;
}
IntCH += IntArray;
IntCGPA = IntValue/IntCH;
out.println(IntCGPA);
}
First, how do i make the results into a new line instead everything in one line?
Adding \n doesn't work and when I run my program it doesn't show my IntCGPA and shows this error
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
at MultiClientHandler1.CGPA(MultiClientHandler1.java:95)
at MultiClientHandler1.View(MultiClientHandler1.java:81)
at MultiClientHandler1.run(MultiClientHandler1.java:116)
You are only printing the file data, not storing in an array.
Try using a method to simply read the file into a list.
private List<String[]> getDataArray(String filename) throws IOException {
List<String[]> data = new ArrayList<>();
InputStream is = getClass().getClassLoader().getResourceAsStream(filename);
Scanner sc = new Scanner(is);
while (sc.hasNextLine()) {
data.add(sc.nextLine().split(":"));
}
return data;
}
Usage:
List<String[]> data = getDataArray("results.txt");
for (String[] array : data) {
System.out.println("1: " + array[1]); // for example
}
I am also trying to make my results display in a new line instead of everything in one line... \n doesnt works
Your code isn't using \n.
String grade ="";
while (...) {
grade += array4[2]+" "+array4[3]+" "+array4[4];
}
out.println(grade);
Try this pattern instead.
StringBuilder grade = new StringBuilder();
while (...) {
// Add columns from array
grade
.append(array4[2]).append(" ")
.append(array4[3]).append(" ")
.append(array4[4]);
// End line
grade.append("\n");
}
out.println(grade.toString());
Anyway, your code throws an exception and stops.
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
at MultiClientHandler1.CGPA(MultiClientHandler1.java:95)
And it tells you the class, method and line number -> at MultiClientHandler1.CGPA(MultiClientHandler1.java:95), so you look there
IntCGPA = IntValue/IntCH;
And think to yourself, "why would I be dividing by zero?" then you see that
IntCH = 0;
IntCH += IntArray;
Which means that IntArray must be zero at some point!
Not really sure what you were trying here.
if(array4[3] == "A") { // This is the string "A"
IntArray = Integer.parseInt(array4[3]); // So, you can't parse an int from "A"
Also Hint: How do I compare strings in Java?
Instead try this
int ch = 0;
int credits = 0;
final int baseCredits = Integer.parseInt(array4[4]);
String grade = array4[3];
switch (grade) {
case "A":
credits = baseCredits * 4;
break;
case "B":
credits = baseCredits * 3;
break;
// etc.
}
int cGPA = baseCredits / credits;
And please don't capitalize your method and variable names and I'd suggest you name intArray or intValue something more descriptive.
So I have a Computer Science course at school in which we learn Java. We were assigned to do a simple text based recreation of the guessing game. I got it done until this point, and I cannot seem to find where I messed up because there is nothing printed when I run the core.
This is the code:
public class GuessGame
{
public static void main(String[] args)
{
new GuessGame();
}
public GuessGame ()
{
char end = 'y';
while (end!='y')
{
System.out.println ("Welcome to the Guessing Game!");
System.out.println ("\nThe computer has picked a number");
System.out.println ("between 1 and 100. Try to guess it.");
int num = (int)(Math.random()*(100-1)+1);
int guess = IBIO.inputInt ("Guess the number: ");
if (guess==num)
System.out.println ("You got it!");
else if (guess>num)
System.out.println ("That is too high.");
else
System.out.println ("That is too low.");
end = IBIO.inputChar ("Exit game? (y/n)");
}
}
}
By the way, IBIO is a class provided by my IB program that we use to make Input/Output statements.
This is IBIO.java:
public class IBIO
{
static void output (String info)
{
System.out.println (info);
}
static void output (char info)
{
System.out.println (info);
}
static void output (byte info)
{
System.out.println (info);
}
static void output (int info)
{
System.out.println (info);
}
static void output (long info)
{
System.out.println (info);
}
static void output (double info)
{
System.out.println (info);
}
static void output (boolean info)
{
System.out.println (info);
}
static String input (String prompt)
{
String inputLine = "";
System.out.print (prompt);
try
{
inputLine = (new java.io.BufferedReader (new java.io.InputStreamReader (System.in))).readLine ();
}
catch (Exception e)
{
String err = e.toString ();
System.out.println (err);
inputLine = "";
}
return inputLine;
}
static String inputString (String prompt)
{
return input (prompt);
}
static String input ()
{
return input ("");
}
static int inputInt ()
{
return inputInt ("");
}
static double inputDouble ()
{
return inputDouble ("");
}
static char inputChar (String prompt)
{
char result = (char) 0;
try
{
result = input (prompt).charAt (0);
}
catch (Exception e)
{
result = (char) 0;
}
return result;
}
static byte inputByte (String prompt)
{
byte result = 0;
try
{
result = Byte.valueOf (input (prompt).trim ()).byteValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static int inputInt (String prompt)
{
int result = 0;
try
{
result = Integer.valueOf (input (prompt).trim ()).intValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static long inputLong (String prompt)
{
long result = 0;
try
{
result = Long.valueOf (input (prompt).trim ()).longValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static double inputDouble (String prompt)
{
double result = 0;
try
{
result = Double.valueOf (input (prompt).trim ()).doubleValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static boolean inputBoolean (String prompt)
{
boolean result = false;
try
{
result = Boolean.valueOf (input (prompt).trim ()).booleanValue ();
}
catch (Exception e)
{
result = false;
}
return result;
}
}
Sorry for the lengthy question. Im new to Java.
The computer is doing exactly what you told it to. When GuessGame's constructor runs:
Declare end as a char local variable and initialise it to contain 'y':
char end = 'y';
Run the loop body while end does not contain 'y':
while (end!='y')
(since end does contain 'y' it does not run the loop body; it skips to the code after the loop).
The problem is that you will never enter the initial loop
char end = 'y';
while (end!='y')
You instantiate end to y, then enter only if end is not y which will always be false, hence never enter the loop.
Simply change the default value of end
char end = 'n';
Also, you don't have to cast the value 0 in your IBIO class
result = (char) 0;
You can simply do result = 0 and it will take the ASCII value.
I would also declare num and guess outside of the loop to avoid re-declaring them each time, as you did for end.
Finally, instead of declaring 7 output method with different paremeter type which simply do a System.out.println of the received parameter I would directly call System.out.println(value).
I would apply the same logic for all other methods that only call one method with the received parameter.
These two lines clearly contradict each other, the while loop will never execute. Initialize end to be a different value.
char end = 'y';
while (end!='y')
You initialize the variable char end with value 'y'.
char end = 'y';
Then the condition for your loop is
while (end!='y')
This condition is never fulfilled, that's why it's out of the loop. Change the initial value of the variable end.
I am working on a problem on UVa for general programming practice, as I want to get better at programming competitively. However I am having trouble with this problem - Roman Numerals. In this problem the goal is to take input which will be in the form of either a Roman numeral or Arabic numeral and then I must convert from one to the other. I feel that my code should not have trouble in processing fast enough yet according to the online judge, it does not process fast enough. I need to help finding out how I may optimize my code so that it will run faster and not receive TLE.
Below is my program, any help as to explaining why I am receiving Time Limit Exceeded would be greatly appreciated. Thanks in advance.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
private static String order = "IVXLCDM";
private static String order2 = "IXCM"; // These chars are the result of 10^n (n depending on index in the string)
private static String order3 = "VLD"; // These chars are products of 5*10^n (n depending on index in the string)
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String ans = "";
while (true) {
String read = "";
int aNum = 0;
String rNum = "";
try {
read = br.readLine();
if (read=="")
break;
} catch (IOException e) {
if (read=="")
break;
e.printStackTrace();
}
try {
aNum = Integer.parseInt(read);
// System.out.println(aNum);
int thousands = aNum/1000;
// System.out.println(thousands);
int hundreds = aNum/100;
hundreds = hundreds%10;
// System.out.println(hundreds);
int tens = aNum%100;
tens = tens/10;
// System.out.println(tens);
int ones = aNum%10;
// System.out.println(ones);
rNum+= a2R(thousands,"M");
rNum+= a2R(hundreds,"C");
rNum+= a2R(tens,"X");
rNum+= a2R(ones,"I");
// System.out.println(rNum);
ans+=(rNum+"\n");
// System.out.print(ans);
} catch (NumberFormatException c) {
rNum = read;
if (rNum.equals(""))
break;
aNum = r2A(rNum);
// System.out.println(aNum);
ans+=(aNum+"\n");
// System.out.print(ans);
}
}
System.out.print(ans);
}
private static int r2A(String rNum) {
int aNum = 0;
for (int i = order.length()-1; i >= 0; i--) {
char curChar = order.charAt(i);
while (rNum.indexOf(curChar)!=-1) {
if (rNum.indexOf(curChar)==0) {
if (order2.indexOf(curChar)!=-1) {
aNum+=((int)Math.pow(10, order2.indexOf(curChar)));
}
else if (order3.indexOf(curChar)!=-1) {
aNum+=(5*((int)Math.pow(10, order3.indexOf(curChar))));
}
rNum = rNum.substring(1);
}
else if (rNum.indexOf(curChar)==1) {
if (order2.indexOf(curChar)!=-1) {
aNum+=((int)(Math.pow(10, order2.indexOf(curChar))-Math.pow(10, order2.indexOf(curChar)-1)));
}
else if (order3.indexOf(curChar)!=-1) {
aNum+=((int)((5*Math.pow(10, order3.indexOf(curChar)))-Math.pow(10,order3.indexOf(curChar))));
}
rNum = rNum.substring(2);
}
}
}
return aNum;
}
private static String a2R(int num, String theNum) {
// num is the digit of an Arabic digit number to be replaced by Roman Numerals for that digit
// theNum is the value of Roman Numerals that would go into the specific digit place (tens, ones,...)
String rNum = "";
if (!theNum.equals("M")) {
if (num==9) {
rNum = theNum + order.charAt(order.indexOf(theNum)+2);
}
else if (num==4) {
rNum = theNum + order.charAt(order.indexOf(theNum)+1);
}
else if (num>=5) {
rNum+= order.charAt(order.indexOf(theNum)+1);
for (int i = 0; i < num-5; i++) {
rNum+=theNum;
}
}
else {
for (int i = 0; i < num; i++) {
rNum+=theNum;
}
}
}
else {
for (int i = 0; i < num; i++) {
rNum+=theNum;
}
}
return rNum;
}
}
`
I expect the TLE is being caused by your program never terminating.
Currently you have a while (true) loop, which breaks when you see a blank line.
According to the problem however...
The input consists of several lines, each one containing
either an Arabic or a Roman number n, where 0 < n < 4000.
Nowhere does it state that there will be an extra blank line terminating the input.
So your program will not terminate, forever waiting until an extra blank line has been entered.
Instead of reading your input like this
while (true) {
String read = "";
int aNum = 0;
String rNum = "";
try {
read = br.readLine();
if (read=="")
break;
} catch (IOException e) {
if (read=="")
break;
e.printStackTrace();
}
//etc
try this instead
String read = "";
while ((read = br.readLine()) != null) {
int aNum = 0;
String rNum = "";
//etc
I solved my problem by going about it in a different manner, I used a couple of HashMaps to map Roman numeral values to Arabic numeral values and vice versa. I had four helper methods: one would set up the hashmaps, another would convert from Roman numeral to Arabic numeral, and the other two would work together to convert from Arabic numeral to Roman numeral.
The method that converted from Roman to Arabic would go through the string in a for loop starting from the beginning of the string. It would check if the length of the string was greater than one, and if so it would then check if the substring of the first two values are in the Roman to Arabic hashmap. If so, it would then add the value that the Roman numeral value equates to to an int variable. The method would also check substrings of length 1.
In the methods that converted from Arabic to Roman, the input integer would first be analyzed then it would be torn apart into its little pieces. In the first method, four integer values would first be produced: the thousands value, the hundreds value, the tens value, then the ones value. The second method would organize these values into the correct Roman numeral form.
Thanks to everybody who helped me solve this problem, I did not realize some of the mistakes that I made, probably due to my inexperience in programming so this was a great learning experience for myself.
Below is my solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
class Main {
private static HashMap<String,Integer> r2A = new HashMap<String,Integer>();
private static HashMap<Integer,String> a2R = new HashMap<Integer,String>();
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
makeMaps();
String read;
StringBuilder answers = new StringBuilder("");
while ((read=br.readLine())!=null) {
int aNum = 0;
String rNum = "";
try {
aNum = Integer.parseInt(read);
System.out.println(arab2Roman(aNum));
} catch (NumberFormatException c) {
rNum = read;
int ans = roman2Arab(rNum);
System.out.println(ans);
}
}
}
private static int roman2Arab(String rNum) {
int aNum = 0;
for (int i = 0; i < rNum.length(); i++) {
boolean done = false;
String theNum = rNum.substring(i,i+1);
if (i < rNum.length()-1) {
String part = rNum.substring(i, i+2);
if (r2A.containsKey(part)) {
aNum+=r2A.get(part);
i++;
done = true;
}
}
if (!done) {
if (r2A.containsKey(theNum)) {
aNum+=r2A.get(theNum);
}
}
}
return aNum;
}
private static String arab2Roman(int num) {
StringBuilder rNum = new StringBuilder("");
int thousands = num-(num%1000);
int hundreds = ((num/100)%10)*100;
int tens = ((num/10)%10)*10;
int ones = num%10;
rNum.append(simpleConv(thousands,"thousands"));
rNum.append(simpleConv(hundreds,"hundreds"));
rNum.append(simpleConv(tens,"tens"));
rNum.append(simpleConv(ones,"ones"));
return rNum.toString();
}
private static String simpleConv(int num, String place) {
StringBuilder ans = new StringBuilder("");
int pNum = (place.equals("thousands")) ? 1000 : (place.equals("hundreds")) ? 100 : (place.equals("tens")) ? 10 : 1;
if (a2R.containsKey(num)) {
ans.append(a2R.get(num));
}
else {
if (num/pNum>=5) {
ans.append(a2R.get(5*pNum));
for (int i = 0; i < ((num/pNum)-5); i++) {
ans.append(a2R.get(pNum));
}
}
else {
for (int i = 0; i < num/pNum; i++) {
ans.append(a2R.get(pNum));
}
}
}
return ans.toString();
}
private static void makeMaps() {
// First r2A
r2A.put("I", 1);
r2A.put("IV", 4);
r2A.put("V", 5);
r2A.put("IX", 9);
r2A.put("X", 10);
r2A.put("XL", 40);
r2A.put("L", 50);
r2A.put("XC", 90);
r2A.put("C", 100);
r2A.put("CD", 400);
r2A.put("D", 500);
r2A.put("CM", 900);
r2A.put("M", 1000);
// Second a2R
a2R.put(1, "I");
a2R.put(4, "IV");
a2R.put(5, "V");
a2R.put(9, "IX");
a2R.put(10, "X");
a2R.put(40, "XL");
a2R.put(50, "L");
a2R.put(90, "XC");
a2R.put(100, "C");
a2R.put(400, "CD");
a2R.put(500, "D");
a2R.put(900, "CM");
a2R.put(1000, "M");
}
}
This is my method that will be called if I want to get a number from user. But if the user also enter a right number just the "else" part will run, why?
Can you explain?
public static int chooseTheTypeOfSorting() {
System.out.println("Enter 0 for merge sorting OR enter 1 for bubble sorting");
int numberFromConsole = 0;
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
DecimalFormat df = new DecimalFormat();
Number n = df.parse(s);
numberFromConsole = n.intValue();
} catch (ParseException ex) {
Logger.getLogger(DoublyLinkedList.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DoublyLinkedList.class.getName()).log(Level.SEVERE, null, ex);
}
return numberFromConsole;
}
and in my main method:
public static void main(String[] args) {
int i = 0;
i = getRandomNumber(10, 10000);
int p = chooseTheTypeOfSorting();
DoublyLinkedList list = new DoublyLinkedList();
for (int j = 0; j < i; j++) {
list.add(j, getRandomNumber(10, 10000));
if (p == 0) {
//do something....
}
if (p == 1) {
//do something.....
} else {
System.out.println("write the correct number ");
chooseTheTypeOfSorting();
}
The problem is you're missing an else
if (p == 0) {
//do something....
} else if (p == 1) { // you're missing the else here
//do something.....
} else {
System.out.println("write the correct number ");
chooseTheTypeOfSorting();
}
On reading number from console
Use java.util.Scanner
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
The documentation has more examples.
Note also that you can set the delimiter, and it also has many hasNextXXX methods that you can use to check against InputMismatchException.
See also
Java Tutorials - I/O - Scanning and Formatting
Design consideration
You may consider having the helper method filter out "bad" input, so that once you get the type of sorting, it's guaranteed to be valid.
You may also consider using an enum:
enum SortMode {
BUBBLE_SORT, QUICK_SORT, BOGO_SORT;
}
See also
Java Tutorials/Enum