Input Mismatch scanner.next(string pattern) from file - file

I'm having a problem while using a
Scanner file = new Scanner(filePath);
my file is organised as so
Question x.y
Answer1
Answer2
Answer3
Answer4
Hint: Hint to Question x.y Level z Genere t
I'm quite new to java and in all of this project I've used
.next(string pattern)
to return a string that includes the parrtern and arrives to the end of the line but i continue to get mismatch exceptions.. i don't really get what
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
defines as token and for this reason i don't know how to handle it..
my code is
public Question getQuestion(String filePath)
{
ArrayList questions = new ArrayList();
Scanner file = new Scanner(filePath);
String questionInFile = "Question";
while(file.hasNextLine())
questions.add(questionInFile+file.next(questionInFile));
Random rg = new Random();
String Q = (String)questions.get(rg.nextInt(10)+1);
file.close();
ArrayList<String> answer=getAnswers(filePath, Q);
String correctAnswer=answer.get(0);
return new Question(Q, answer, correctAnswer);
}

try adding
File filePath = new File(".txt");
before Scanner file

Related

How can I get whole string value from List in apex

I need your help.
I made an apex class which is giving output like (1,i,n,d,i,a,,1,2,3) and I would like to show output as a whole string format like(1india 123). I tried many different ways but couldn't get what I actually want.
Here is my apex class:-
public class Assign2{
public void testFunction(String str ,integer num){
integer rem,temp = 0;
integer sumOfDigit = 0;
List<String> stringCharacters = new List<String>();
List<String> inputStr = new List<String>();
stringCharacters = str.split('');
System.debug('stringCharacters::'+stringCharacters);
for(integer i=0; i<stringCharacters.size(); i++){
if(stringCharacters[i].isNumeric()){
temp = Integer.valueOf(stringCharacters[i]);
//System.debug('temp::'+temp);
rem = temp +num;
//System.debug('rem::'+rem);
sumOfDigit = math.mod(rem,10);
//System.debug('sumOfDigit::'+sumOfDigit);
stringCharacters[i] = sumOfDigit+'';
//System.debug('ans::'+stringCharacters);
}
}
System.debug('ans::'+stringCharacters);
}}
and I run the program by giving input:-
Assign2 obj = new Assign2();
obj.testFunction('2india 234',9);
help will be appreciable.
Thank You.
You've used split with empty string as parameter (meaning you want to cut it into 1-character strings). All you have to do is to reverse the process with join.
List<String> characters = new List<String>{'1','i','n','d','i','a',' ','1','2','3'};
String word = String.join(characters, '');
System.debug(word); // "1india 123"

Get files names and content , and then merge into another file with mapreduce

I have several files with datas in it.
For example: file01.csv with x lignes in it, file02.csv with y lines in it.
I would like to treat and merge them with mapreduce in order to get a file with the x lines beginning with file01 then line content, and y files beginning with file02 then line content.
I have two issues here:
I know how to get lines from a file with mapreduce by setting FileInputFormat.setInputPath(job, new Path(inputFile));
But I don't understand how I can get lines of each file of a folder.
Once I have those lines in my mapper, how can I access to the filename corresponding, so that I can create the data I want ?
Thank you for your consideration.
Ambre
You do not need map-reduce in your situation. That's because you want to preserve the order of lines in result file. In this case single thread processing will be faster.
Just run java client with code like this:
FileSystem fs = FileSystem.get();
OutputStream os = fs.create(outputPath); // stream for result file
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
for (String inputFile : inputs) { // reading input files
InputStream is = fs.open(new Path(inputFile));
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
}
br.close();
}
pw.close();

Importing 2 types of variables from text file

I am not very fluent, simple question: when i have text file like this:
Name number
Name2 number2
How do i import it to Arrays, that I can operate on both of these? Numbers and names are separated by space. I have seen guides just to one type of variable, but what if i have two of them?
In pseudocode
while not eof:
read name
do sth with name
read number
do sth with number
In Java
String line;
String[] row;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
while ((line = br.readLine()) != null) {
row = line.split("\\s+");
names.add(row[0]);
numbers.add(Integer.parseInt(row[1]));
}
} catch (IOException e) {}

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

Read data from csv file using java in webdriver

How to read data of each cell in Selenium WebDriver using Java?
I have tried with following code:
CSVReader reader = new CSVReader(new FileReader("D:/data1.csv"));
expectedLabels = reader.readNext();
FieldNames = reader.readNext();
FieldValues = reader.readNext();
File file = new File("D:/data.csv");
if(file.exists()){
System.out.println("File Exists");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
while((line = bufRdr.readLine()) != null){
StringTokenizer st = new StringTokenizer(line,",");
col=0;
while (st.hasMoreTokens()){
//Following stroing the data of csv
numbers[row][col] = st.nextToken();
col++;
}
System.out.println();
row++;
}
bufRdr.close();
reading csv files become very easy with OPENCSV jar file. I have used this jar file couple of time to read file.
We have predefined class called CSVReader, create an object and pass the csv file path
call readAll() method which will return the csv content in List
using Iterator, you can iterate all the values and use according to application
I have written article on this have a look it might help you.
http://learn-automation.com/how-to-read-csv-files-using-java/
I am not able to provider string type variable in FileReader() function , it shows error while passing filereader() method with parameter in buffer reader fn
code shown below:
String f1= (System.getProperty("User.dir") + "\\Module9TestNG\\src\\TestLogin.xlsx");
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String record;
String url= null;
while ((record = bufRdr.readLine()) != null)
{
String fields[] = record.split(",");
url= fields[0].toString();
}
private String Fpath ="D:\\CkycApps.csv";
String line;
File file = new File(Fpath);
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
while((line = bufRdr.readLine()) != null){
System.out.println(line);
String[] cell= line.split(",");
String FirstName=cell[0];
String MiddleName=cell[1];
}

Resources