Issue reading integers from file using Scanner - java

I am having an issue reading integers from an input file using scanner. Here is the bit of code I am having trouble with:
String path = sc.nextLine();
File filename = new File(path);
Scanner reader = null;
reader = new Scanner(filename);
for(int i = 0; i < 4; i++)
{
while(reader.hasNextInt())
{
System.out.println(reader.nextLine());
pid[i] = reader.nextInt();
arrivaltime[i] = reader.nextInt();
burstTime[i] = reader.nextInt();
}
}
The input file I am using contains this information:
1 1 1
2 2 2
3 3 3
4 4 4
Using this file, I am trying to make it so that pid[] = [1,2,3,4], arrivaltime[] = [1,2,3,4] and bursttime[] = [1,2,3,4]. However, each of these arrays are instead being shown as [4,0,0,0] and I can't figure out why for the life of me. Any help would be appreciated.

Try this:
Read the line first
Then split it!
int i = 0
while(reader.hasNextLine()){
String[] line = reader.nextLine().split(" ");
pid[i] = Integer.parseInt(line[0]);
arrivaltime[i] = Integer.parseInt(line[1]);
burstTime[i] = Integer.parseInt(line[2]);
i++;
}

When you use scanner.nextLine() the scanner pointer in the file skips first line.
You can use this if you don't want to print each line or use the other solution with splitting.
int i = 0;
while(reader.hasNextInt()) {
pid[i] = reader.nextInt();
arrivaltime[i] = reader.nextInt();
burstTime[i] = reader.nextInt();
i++;
}

Try This:
for(int i = 0; i < 4; i++)
{
if (reader.hasNextInt()) {
pid[i] = reader.nextInt();
arrivaltime[i] = reader.nextInt();
burstTime[i] = reader.nextInt();
}
}

Related

asking for a name of each customer with array size in for loop

I'm a beginner and I've been really stuck on this problem. I'm not really sure how I can display the number of customer(in an arraySize) (customer #1, customer #2...) and ask for their name in a for loop.
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + arraySize + ": "
}
I've tried dinerArray.length and then i, arraySize with i, (i=0;i<=arraySize;i++) with arraySize/i.. but nothing seems to work. It would either only print once with customer#0 or print nothing at all
You need to change arraySize to i. That way it will produce customer#1,customer#2 etc....
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + i+ ": ");
}
If you just want to read them from the console, you can use a Scanner:
Scanner input = new Scanner(System.in);
int arraySize = 10;
String[] dinerArray = new String[arraySize];
for(int i = 0; i < arraySize; ++i)
{
System.out.print("Enter the name of customer#" + (i + 1) + ": ");
dinerArray[i] = input.nextLine();
}
input.close();
im no Java dev but this is pretty basic.
The problem is that your for loop is just running if i is equal to arraySize, but this never happen.
So, try to change your '==' to a '<='
My solution:
Scanner scan = new Scanner(System.in);
int arraySize = 5;
String[] dinerArray = new String[arraySize];
for(int i = 1; i <= dinerArray.length; i++) {
ystem.out.print("pleas enter name for customer#" + i);
dinerArray[i - 1] = scan.nextLine();
}
Im not sure about the scanner think.

Java Mult Array From File

I have been having problem trying to get the program to work. The first row in the array is set blank and it keep pushing out the last row in the array.
Scanner console = new Scanner(System.in);
System.out.println("please enter the file name");
String name = console.next();
Scanner input = new Scanner(new File(name));
int length = input.nextInt();
int lengt = input.nextInt();
char[][] array = new char[length][lengt];
for(int i = 0; i < length; i++) {
array[i] = input.nextLine().toCharArray();
}
for(int k = 0; k < array.length; k++){
for(int s = 0; s < array[k].length; s++) {
System.out.print(array[k][s]);
}
System.out.println();
}
input.close();
System.out.println();
Try the adding the line input.nextLine(); to your code like so:
int length = input.nextInt();
int lengt = input.nextInt();
input.nextLine();
char[][] array = new char[length][lengt];
I believe what is happening is you are reading the int's to get length and lengt, but you are leaving the rest of that line. When you call array[i] = input.nextLine().toCharArray(); the first time you are pushing the rest or the line with the length and lengt int's. Since that is counted as the first line in your for loop you are not iterating over the last line.

How is my String Index Out of Bounds?

GOAL: To ask user for # of points. Then user will input "1 4", where 1 is the x and 4 is the y. I will take the sub-string to get 1 and 4 separately then make them an int so I can make them a Point.
I keep getting "java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
this is taking place on line 25, but not 24. When I use 3 instead of the length it also gives me this error.
This is a fragment of code:
public String run() {
String line = "";
String first = "";
String second = "";
int j = 0; int n = 0;
System.out.println("How many inputs do you want to enter?");
Scanner sc = new Scanner(System.in);
while(j == 0){
if(sc.hasNextInt()){
n = sc.nextInt();
Point[] points = new Point[n];
sc.close();
j++;
}
else {
System.out.println("invalid input");
}
}
Scanner scan = new Scanner(System.in);
for(int i = 0; i <= n; i++){
System.out.println("Enter x and y:");
line = scan.next();
first = line.substring(0,1);
second = line.substring(2,line.length());
}
scan.close();
origin(points);
return "";
}
See if this works for you. I'm not sure what your j variable was doing, your for-loop for the points was going out of bounds on the array, you are closing System.in between two separate Scanners, and obviously something wrong is happening with your substring logic.
This code fixes all those problems and runs great for me.
public String run() {
Scanner sc = new Scanner(System.in);
int n = numberPrompt("How many inputs do you want to enter?\n", "Invalid input");
Point[] points = new Point[n];
for(int i = 0; i < n; i++){
System.out.println("Enter x and y:");
String line = sc.nextLine();
String[] data = line.split("\\s+");
if (data.length >= 2)
{
int x = Integer.parseInt(data[0]);
int y = Integer.parseInt(data[1]);
points[i] = new Point(x, y);
}
}
System.out.println(Arrays.asList(points));
origin(points);
return "";
}
private int numberPrompt(String prompt, String error) {
Integer number = null;
boolean isValid;
String input;
Scanner sc = new Scanner(System.in);
do {
isValid = true; // reset the validity
System.out.print(prompt);
input = sc.nextLine();
try {
number = Integer.parseInt(input);
} catch (NumberFormatException e) {
isValid = false;
if (!(error == null || error.isEmpty())) {
System.out.println(error);
}
}
} while (!isValid);
return number;
}

Enter multiple numbers in console

So i have the following chuckj of code and what i want it do is for the user to enter 5 numbers in the netbeans console.The way i want to do it is he either can enter some by being separting the numbers with a space or line by line for exmaple like the following
But what i want is to "Enter a string of numbers" to be only visiable when it is needed to, for example when he needs to enter the next number. Is it possible to do this?
The following is done by the following code
Scanner reader = new Scanner(System.in);
int number;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 5; i++) {
System.out.println("Enter a string of numbers");
number = reader.nextInt();
numbers.add(number);
}
System.out.println("size" + numbers.size());
for(int takenNumber : numbers){
System.out.println(takenNumber);
}
You could do something like this:
Scanner reader = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
int numbersEntered = 0; // Stores how many numbers the user has entered so far
while (numbersEntered < 5) { // Keep asking if they have not entered 5 numbers yet
System.out.println("Enter a string of numbers");
String[] input = reader.nextLine().split(" "); // Split the input by spaces into an array
numbersEntered += input.length; // Add the number of numbers they entered to the variable
for (int i = 0; i < input.length; i++) {
if (numbers.size() < 5) { // Only add the numbers if the list is not full
numbers.add(Integer.parseInt(input[i])); // Add each number they entered to the numbers list
}
}
}
You can use the hasNext() function of Scanner to keep reading while there is more input without doing another prompt. Try:
Scanner reader = new Scanner(System.in);
int number;
ArrayList<Integer> numbers = new ArrayList<Integer>();
int i = 0;
while((i < 5))
{
System.out.println("Enter a string of numbers:");
if(reader.hasNextLine())
{
String[] numbersRead = reader.nextLine().split("\\s");
System.out.print("Read:");
for(int n = 0; n < numbersRead.length; n++)
{
numbers.add(Integer.parseInt(numbersRead[n]));
i++;
}
System.out.println();
}
}

How to load String by BufferedReader?

I need to load in a given String which will be type in as an input Stringļ¼š
20 6
....................
..XXXXX..XXX.XXX..X.
..X.X.X..X.XXX.X..X.
..XXXXX..XX.X..X....
..XX......XXXXXX..X.
....................
something like that. It contains 2 integers and a String with "." and "X"
Now I just want to ask 2 questions:
1)I need to load the 2 integers first,but how can get the first two integers by BufferedReader?(the 2 int is divide by space between each other and the rest)
2)Then after loading the two integers,how can I load the following rest string char by char?(Like everytime I need to just load one char,then I go to some function,then come back and load the next char;and between there is no blank space)
Here is part of my code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
number1 = Integer.parseInt();
number2 = Integer.parseInt();
And now I don't know how to continue...Anyone can help me to load it?
For 1) you just need to do a split
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
String ints[] = str.split(" ");
number1 = Integer.parseInt( ints[0] );
number2 = Integer.parseInt( ints[1] );
Then for 2) once you have a String you can have it length and so get them char by char ;)
String lol = "......XXX..XX...";
for( int i = 0; i < lol.length(); i++ )
System.out.println(lol.charAt(i));
With this you will get all your string char by char
It is much better if you use Scanner then you can read int and the String easier.
I suppose you input two integers as col and row.
Example like this:
Scanner scan = new Scanner(System.in);
int col = scan.nextInt();
int row = scan.nextInt(); //input two int first
scan.nextLine();
for(int i = 0; i < row; i++) {
String s = scan.nextLine();
for(int j = 0; j < col; j++) {
char c = s.charAt(j);
//your code here
}
}

Categories

Resources