Decision making and loop - java

I am brand new to Java (2 weeks), basically I am trying to do a Triangle problem. I need to input a text file that looks like this:
2 2 2
3 3 2
3 x 4
I can make it read the file and display it correctly, however I need it to display "Equilateral" " Isosceles" "Scalene" or not a triangle because... I cannot figure out how to get my outputs based on the input from the text file. Here is what I have so far.
public static void main(String[] args) throws Exception
{
File file =
new File("input.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
Which is basically nothing. I know I need 3 arrays. Can someone jumpstart me in the right direction?
Thanks

You need to set sc.nextLine() to a variable to use instead of printing it out as an output immediately. If the sets of three numbers come in a single line, you may want to utilize the split() method, which is pretty easy to use when you understand arrays.
To get you started:
public static void main(String[] args) throws Exception
{
File file =
new File("input.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
String firstLine = sc.nextLine();
String[] sides = firstLine.split(" ");// Get the numbers in between the spaces
// use the individual side lengths for the first triangle as you need
// Next iteration works through the next triangle.
}

You're headed in the right direction. I suggest checking out the following methods:
String.split() docs here
Integer.parseInt() docs here
Those, combined with a little bit of your own logic, should be enough to get you across the finish line.

Related

Why am I getting an InputMismatchException with?

I created a Scanner in java to read through a file of data regarding a city. The file is formatted as such:
Abbotsford,2310,2
Adams,1967,1
Algoma,3167,2
When reading through the file, I get an InputMismatchException when scanning the last item on each line (This item needs to be an int).
public void fileScanner(File toScan) throws FileNotFoundException {
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",");
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
Any ideas as to why? I'd imagine it has something to do with my use of the "," delimiter.
You are using only one delimiter i.e. , but your file contains \r or \n so try to use multiple delimiters. Also, use a loop to read the entire file:-
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",|\\r\\n");
while (sc.hasNext()) {
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
}
OUTPUT:-
Abbotsford
2310
2
Adams
1967
1
Algoma
3167
2
The delimiter you're using is comma(,)
The system looks for the next comma, which comes only after Adams. So the input for the system looks like 2 Adams which is obviously not an Int , rather a String and hence the inputMisMatch.
If you make your data something like below, your code would work great.
Abbotsford,2310,2,
Adams,1967,1,
Algoma,3167,2,
Also I see there's no loop to read all the data. Your code will read just the first line.

Split String input from file into an array using scanner

I have a textfile that i am reading out of that looks like this:
pizza, fries, eggs.
1, 2, 4.
I am scannning this .txt using the Scanner class and i want to insert the input into an ArrayList. I know that there is a method to split Strings and use the "," as a Delimiter but i cannot seem to find how and where to apply this. Note: The . is used as its own Delimiter so the scanner know it needs to check the next Line and add that to a different ArrayList.
Here is my corresponding code from the class with the ArrayList Setup:
public class GrocerieList {
static ArrayList<String> foodList = new ArrayList<>();
static ArrayList<String> foodAmount = new ArrayList<>();
}
And here is the code from the class scanning the .txt input:
public static void readFile() throws FileNotFoundException {
Scanner scan = new Scanner(file);
scan.useDelimiter("/|\\.");
scan.nextLine(); // required because there is one empty line at .txt start
if(scan.hasNext()) {
GrocerieList.foodList.add(scan.next());
scan.nextLine();
}
if(scan.hasNext()) {
GrocerieList.foodAmount.add(scan.next());
scan.nextLine();
}
}
Where can i split the strings? And how? Perhaps my approach is flawed and i need to alter it? Any help is greatly appreciated, thank you!
Use nextLine() to read a line from the file, then eliminate the ending period, and split on comma.
And use try-with-resources to close the file correctly.
public static void readFile() throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.nextLine(); // required because there is one empty line at .txt start
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
GrocerieList.foodAmount.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
}
}
Usually you would save the read out from the nextLine method, and use the split method to decompose the list into an array, then store it to your target. If conversion is needed, such as from string to integer, do it separately.
String lineContent = scan.nextLine();
String[] components = lineContent.split(","); //now your array has "pizza", "fries", "eggs" etc.
The easiest way to do this would be to use String#split.
Also you don't want 'next', but nextLine
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(", ")));
(Should work but didn't test it).
For more informations about the scanner class refer to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Trying to read csv file into ArrayList in Java but elements are unintentionally merging?

I have a csv file that contains values that im trying to put into an arraylist but the last value of a line merges with the first value of the second line.
See:
I have data like this,
Account Number,Investment Account,Bank Number,Gender,Balance
2544434, Y, 145556, F,1000
2544578, N, 254309, M, 20000
2544230, N, 150365, F, 500000
and my code so far is this,
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
List<String> list = new ArrayList<String>();
try {
Scanner sc = new Scanner(new File("data.csv"));
sc.useDelimiter(",");
sc.nextLine();
while(sc.hasNext()) {
list.add(sc.next());
}
System.out.println(list.get(4))
}
The output looks like this,
1000
2544578
with both the last and first value of their respective rows merging into one when i'd like to keep it separate. I've searched for similar questions and could not find any so i wonder if anyone here can possible help. I'd like this to be done using Scanner module.
In this case, you have already pointed out that a new line does not separate each element of the CSV format.
To fix this you can use the overloaded method of useDelimiter to supply a pattern, wherein the delimiter is either a comma followed by a space or a new line.
Some regex like so:
,\W|[\n]

Java ArrayList, taking user input of multiple types(int, String etc.) in one line

I'm working on getting a little better at Java, and a problem I've run into is taking user input, all in one line like this:
System.out.println("Please input numbers that you would like to work with");
//Read in user input into ArrayList, taking into account that they may input Strings or anything else.
Assuming the user inputs something like this
1, 2, 4, 257, dog, rabbit, 7, #
or even
1 2 4 257 dog rabbit 7 #
I've seen in several places how to read in one input at a time, but I wasn't sure of the best way to read in a dynamic ArrayList all at once.
I'm not really concerned with the difference in doing it with commas or without commas since logically I think I know how to do that, and haven't tried yet, so really the main problem is as stated above (reading user input into ArrayList of dynamic size when user inputs all numbers at once). Thanks, and I'm not necessarily looking for code, this isn't homework, just wondering best way to do this. Just stating logically how it's done will work, but code is appreciated.
try this simple example to print the arraylist values
import java.util.*;
class SimpleArrayList{
public static void main(String args[]){
List l=new ArrayList();
System.out.println("Enter the input");
Scanner input=new Scanner(System.in);
String a =input.nextLine();
l.add(a);
// use this to iterate the value inside the arraylist.
/* for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
} */
System.out.println(l);
}
}
As I think there are enough answers on how to read data from System.in, I'll take a different approach here. First you should be aware that this is not the major way of getting data in java. In fact in more than 10 years I never used it. That's why there's no complete ready to use solution for give me the stuctured data into some container (like ArrayList). Instead you get simply one string per line. And you have to deal with that on your own. this process is called parsing. Depending on the complexity of the chosen syntax there are several approaches like using a parser generator if it's more complex or write the parser by hand in simpler case. I'd like to get into your first suggestion and describe it as comma separated with optional whitespace. For a syntax like this the class Scanner delivers quite some support. Numbers can be recognized and the tokenizing is done almost automatic. However, if you have more specific data you might need some aditional effort, like I demonstrated with a map of animals I used to convert that very special data type. To be flexible enough to solve all the real world problems there can't be a ready to use solution. Only comprehensive support to build your own.
Map<String, Animal> animals = ...
Scanner scanner = new Scanner("1, 2, 4, 257, dog, rabbit, 7, #").useDelimiter(",");
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
result.add(scanner.nextInt());
} else {
String val = scanner.next();
if (animals.containsKey(val)) {
result.add(animals.get(val));
} else {
result.add(val);
}
}
}
you can try this code for taking input dinamically in arraylist and store in arraylist
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String []args){
Scanner sc=new Scanner(System.in);
String j;
ArrayList l=new ArrayList();
for(int i=0;i<6;i++)
{ j=sc.nextLine();
l.add(j);
}
System.out.println("Hello World"+l);
}
}
One approach is to tokenize the input and then add it into an array like this:
Scanner scn = new Scanner(System.in);
System.out.println("Put in a set: ");
String input = scn.nextLine();
System.out.println(input);
Scanner tokenizer = new Scanner(input);
tokenizer.useDelimiter(" ");
ArrayList<Object> arr = new ArrayList<Object>();
while(tokenizer.hasNext())
{
arr.add(tokenizer.next());
System.out.println(arr.get(arr.size()-1));
}
System.out.println(arr);

Using Scanner to read file

I am using Scanner to read the text file which contains *, spaces and alphabets. Two or more spaces can occur one after the other. Eg:
**** AAAAA* * ****
******* AAAAAA*** *
I have written the following code:
lineTokenizer = new Scanner(s.nextLine());
int i=0;
if (lineTokenizer.hasNext()) {
//lineTokenizer.useDelimiter("\\s");
System.out.println(lineTokenizer.next());
//maze[0][i]=lineTokenizer.next();
i++;
}
The lineTokenizer doesn't read beyond the * from the input file not are the characters getting stored in the maze array. Can you tell me where I'm going wrong? Thanks!
You could also use FileInputStreams to read the file with a BufferedReader.
I personnally use the Scanner only for console input.
I think you should be using loops instead of just if.
Try changing the 3rd line to:
while (lineTokenizer.hasNext())
Since you are using an if condition, the pointer is not moving ahead. You should use a loop to continuously read data from scanner. Hope that helps.
I guess the code is changed many times while you tried different stuff.
I don't know how you handle the initialization of maze but to avoid any ArrayIndexOutOfBounds I would use a List in a List instead.
I made some guesses about what you wanted and propose this:
List<List<String>> maze = new ArrayList<>();
Scanner s = new Scanner("**** AAAAA* * ****\n ******* AAAAAA*** *");
while (s.hasNextLine()) {
List<String> line = new ArrayList<>();
Scanner lineTokenizer = new Scanner(s.nextLine());
lineTokenizer.useDelimiter("\\s+");
while (lineTokenizer.hasNext()) {
String data = lineTokenizer.next();
System.out.println(data);
line.add(data);
}
lineTokenizer.close();
maze.add(line);
}
s.close();
I did not fully understand your goals. Does this do about what you want?
The code above will give you the following list: [[****, AAAAA*, *, ****], [*******, AAAAAA***, *]]

Categories