Java input nextLine after another nextLine - java

Code:
public void addTest(int idUser) throws IOException {
String date = null;
String tec = null;
System.out.println("Enter name for test file :");
String file = input.next(); //Name of file
System.out.println("Enter date formatted as dd/mm/yyyy hh:mm :");
date = input.nextLine(); //String 2 parts
input.next();
System.out.println("Enter technician name :");
tec = input.nextLine(); // String 2+ parts
input.next();
String path = "C:\\Test\\Sample\\" + file;
String chain = readFile(path);
ClinicalTest test = new ClinicalTest(chain, date, idUser, tec);
System.out.println(test.getDate()+"\n" + test.getTec());
createTest(test);
}
When enter date 12-12-2018 13:45 and tec name Mark Zus, trying to create test fails.
sysout only shows 13:45.
I tried input.next() under each nextLine() because if I don't, never let me complete date field.
This is what happen if only use nextLine() for each entry

I suggest you to read JavaDoc which is helpful in using methods. As it is written above the nextLine() method:
This method returns the rest of the current line, excluding any line
separator at the end. The position is set to the beginning of the next
line.
It means that by using next() method you are reading the first part of your input and then when you use nextLine() it captures the rest of the line which is 13:45 in your input sample.
So you don't need input.next(). The following code works perfectly:
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String date = null;
String tec = null;
System.out.println("Enter name for test file :");
String file = input.nextLine();
System.out.println("Enter date formatted as dd/mm/yyyy hh:mm :");
date = input.nextLine(); //String 2 parts
System.out.println("Enter technician name :");
tec = input.nextLine(); // String 2+ parts
}

Related

How can I check if the character from a user- inputted string (first string) is present on the second string?

We have to write a program that inputs two String values. And this is the condition:
If the third character of the first string is present on the second string then do this code...
I tried using the .contains() method but there is an error. I also don't know how to apply loops because the output is being printed several times. What should I do?
The error says "The method contains (CharSequence) in the type String is not applicable for the arguments (char)"
System.out.println("Input String 1:");
Scanner sc1 = new Scanner(System.in);
String str1 = sc1.nextLine();
System.out.println("Input String 2:");
Scanner sc2 = new Scanner(System.in);
String str2 = sc2.nextLine();
char third = str1.charAt(2);
if (str2.contains(third)) {
str1 = str1.replaceAll("[AaEeIiOoUu]", "*");
str1.replaceAll("[AaEeIiOoUu]", "*");
System.out.println(str1.toUpperCase());
String first = "xyz";
String nthChar = Character.toString(first.charAt(2);
String second = "aaaaaaaz";
if(second.indexOf(nthChar) != -1){
// nth character from 'first' exists in 'second'
// do whatever
}

String in ArrayList Not Outputting

I have the following method which takes user input and applies an algorithm to it. However when I try to print the String process_name, stored in the fcfs ArrayList it comes out empty. But the burst_time and arrival_time fields in the same fcfs ArrayList get output to the console exactly as the user inputted the data. Not really sure what could be wrong.
public static void algorithm() {
ArrayList<Process> fcfs = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Process name,CPU Burst Time,Arrival time\n ");
while (!scan.next().equalsIgnoreCase("finish")) {
Process p = new Process();
String pn = "";
String bt = "";
String at = "";
pn = input.nextLine();
bt = input.nextLine();
at = input.nextLine();
System.out.println("Process name, CPU Burst Time, Arrival time\n ");
p.process_name = pn;
p.burstTime = Float.parseFloat(bt);
p.arrivalTime = Float.parseFloat(at);
fcfs.add(p);
}
{
Collections.sort(fcfs, new comp());
}
result(fcfs, fcfs.size(),false)
}
This is the Process class:
class Process {
String process_name;
float burstTime;
float arrivalTime;
float compTime = 0;
boolean status = false;
}
scan.next() function gets the next input string. That is why you get an empty line for process name because the name is already taken by the next function in the while condition. Either use hasNext() to check if there is a next line or get and put input to a string variable and compare it with the word 'finish'.
You can see the explanation in the documentation: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
Quoting from the documentation: "next : Finds and returns the next complete token from this scanner"
The problem is because of using next() instead of nextLine(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Replace
while (!scan.next().equalsIgnoreCase("finish"))
with
while (!scan.nextLine().equalsIgnoreCase("finish"))
Also, it's better to use do...while which guarantees to execute its body at least once i.e.
do {
Process p = new Process();
String pn = "";
String bt = "";
String at = "";
pn = input.nextLine();
bt = input.nextLine();
at = input.nextLine();
System.out.println("Process name, CPU Burst Time, Arrival time\n ");
p.process_name = pn;
p.burstTime = Float.parseFloat(bt);
p.arrivalTime = Float.parseFloat(at);
fcfs.add(p);
} while (!scan.nextLine().equalsIgnoreCase("finish"));

How to convert a text file to array object? Java

I am working on a program that takes in a text file and converts it to a team roster. The text file has unknown length, first name, last name, offence score, and defense score. the name and scores are on the same line. Rachael Adams 3.36 1.93. I can not figure out how to convert each line of the text file into an object. I've searched the internet and all of the examples just have one value per a line and converts it into one big array. I've included some extra imports in the code because i know that I will need them further on in the project(find best attackers, best defenders, make teams of 6, print teams). I've modified code from previous projects that took in numbers separated by lines.
class VolleyballFile {
String fileName;
int count;
String currentFileName;
String outputFile="";
String firstName;
String lastName;
double attackScore;
double defenceScore;
Scanner input = new Scanner(System.in);
public VolleyballFile() throws FileNotFoundException {
System.out.println("Please enter a file name to get the roster from");
this.fileName = input.nextLine();
File file = new File(fileName);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()){
int result = Integer.parseInt(scan.nextLine());
this.count+=1;
}
}
}
Using the command String.split(); you can split a string up to an array of strings. So:
while (scan.hasNextLine()) {
//int result = Integer.parseInt(scan.nextLine());
string[] line = scan.nextLine().split(" ");
firstName = string[0];
lastName = string[1];
attackScore = Float.Parse(string[2]);
defenceScore = Float.Parse(string[3]);
this.count+=1;
}
I'm not sure if you can Float.Parse(), don't remember since I haven't used java recently.

check for valid user input string and read the string with spaces using scanner in java

I am getting user input for the string variable street and trying to check whether it contains only strings and no special characters. And then I am assigning it to a string variable "street". But when the user types, for example "La Jolla" it considers only "La" and ignores "Jolla". How should I modify the code so that it checks for valid input string and also considers space and assigns street variable with "La Jolla" and also if the street name is just "Montclair" without any more words
System.out.println("Please enter the street name>> " );
while(!sc.hasNext("[a-zA-Z]+")){
System.out.println("Please enter a valid street name>> " );
sc.next();
}
String street = sc.nextLine();
hasNext("[a-zA-Z]+") only checks if there is a token matching your expression, not if an entire line is available.
next() gets the next token from the scanner, not next line.
No real use for Scanner in this scenario.
This will work:
BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); // Optionally add a charset as 2nd parameter.
String street;
while (true) {
System.out.println("Please enter a valid street name>> " );
try {
String line = r.readLine();
// Accept a line with alphabetic characters delimited with space.
if (line.matches("[A-Za-z ]+$")) {
street = line;
break;
}
} catch (IOException e) {
// Handle broken input stream here.
street = "";
e.printStackTrace();
break;
}
}
System.out.println(street);
sc.next() finds and returns the next complete token from the current scanner 'sc'.
Scanner has a method nextLine() which advances the scanner past the current line and returns the input that was skipped.
You need to use nextLine() in your case , so you can get past the interval.
You can do that with simple code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the street name>> ");
String street = sc.nextLine();
while (!isAlphabet(street)) {
System.out.println("Please enter a valid street name>> ");
street = sc.nextLine();
}
System.out.println(street);
sc.close();
}
public static boolean isAlphabet(String s) {
return s.matches("[a-z A-Z]+");
}
Output
> Please enter the street name>>
> La Jolla%
> Please enter a valid street name>>
> La Jolla
> La Jolla

Searching for string in file and returning that specific line

I am working on student registration system. I have a text file with studentname, studentnumber and the student's grade stored in every line such as:
name1,1234,7
name2,2345,8
name3,3456,3
name4,4567,10
name5,5678,6
How can I search a name and then return the whole sentence? It does not get any matches when looking for the name.
my current code look like this:
public static void retrieveUserInfo()
{
System.out.println("Please enter username"); //Enter the username you want to look for
String inputUsername = userInput.nextLine();
final Scanner scanner = new Scanner("file.txt");
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +inputUsername+ " in file " ); // this should return the whole line, so the name, student number and grade
break;
}
else System.out.println("Nothing here");
}
The problem is with Scanner(String) constructor as it:
public Scanner(java.lang.String source)
Constructs a new Scanner that produces values scanned from the
specified string.
Parameters: source - A string to scan
it does not know anything about files, just about strings. So, the only line that this Scanner instance can give you (via nextLine() call) is file.txt.
Simple test would be:
Scanner scanner = new Scanner("any test string");
assertEquals("any test string", scanner.nextLine());
You should use other constructor of Scanner class such as:
Scanner(InputStream)
Scanner(File)
Scanner(Path)
You already have the variable that holds the whole line. Just print it like this:
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +lineFromFile+ " in file " );
break;
}
else System.out.println("Nothing here");
}

Categories