Saving keyboard input as variable - java

I want to know how I could take keyboard input and save it as a variable so I can use it with the code below.
Code:
public void readMaze(){
Scanner reader = null;
try {
reader = new Scanner(new FileReader("Maze.txt"));
colSize = reader.nextInt();
rowSize = reader.nextInt();
finishRow = reader.nextInt();
finishCol = reader.nextInt();
startRow = reader.nextInt();
startCol = reader.nextInt();
Instead of having "Maze.txt" I want to have a variable there that can change every time I run the program so I won't have to keep editing the program when I want to use a different file.

You can capture the file name using your Scanner itself:
System.out.println("Please input the file name to use: ");
Scanner reader = new Scanner(System.in);
String fileName = reader.next();
Then proceed with your method as usual, reusing the same Scanner variable for a new Scanner object, this time passing filename you captured earlier:
try {
reader = new Scanner(new FileReader(fileName));
...
}
With this, you'll be able to dynamically change the filename while your program is running.

I would probably use command line arguments:
public static void main(String[] args)
{
final String mazeFilename = args[0]; // perhaps check if args.length > 0
...
}
then
java YourPrgm Maze.txt

You could try scanning them in through the console and changing them from Strings to ints.
public static void main(String[] args) {
int colSize, rowSize, finishRow, finishCol, startRow, startCol = 0;
// note, through console
Scanner in = new Scanner(System.in);
System.out.print("Enter colSize:");
colSize = Integer.parseInt(in.nextLine());
System.out.print("Enter rowSize:");
rowSize = Integer.parseInt(in.nextLine());
System.out.print("Enter finishRow:");
finishRow = Integer.parseInt(in.nextLine());
System.out.print("Enter finishCol:");
finishCol = Integer.parseInt(in.nextLine());
System.out.print("Enter startRow:");
startRow = Integer.parseInt(in.nextLine());
System.out.print("Enter startCol:");
startCol = Integer.parseInt(in.nextLine());
}
}

Related

Counting and resetting a Scanner

I'm an amateur with Java and am trying to put the contents of a scanner into an array. This is what I have currently:
`
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int l = scannerLength(sc);
sc.close(); sc = null; sc = new Scanner(System.in);
int[] input = new int[l];
for (int i = 0; i < l; i++) {
input[i] = sc.nextInt();
System.out.println(input[i]);
}
}
private static int scannerLength(Scanner sc) {
int output = 0;
while(sc.hasNextInt()) {
output++;
sc.nextInt();
}
return output;
}
`
I am trying to effectively 'reset' the Scanner after my helper function determines its length by voiding it and declaring it anew, so I can use nextInt to put the elements into an array. But I get a NoSuchElementException at line 8.
Can anyone tell me why this is? I would think, after resetting the Scanner, that sc.nextInt() at line 8 wouldn't pose a problem.

i have a for loop that does not wait for input before continuing [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
i have a block of code that is supposed to ask a question, get input THEN ask the next question. Not only does this code not wait for the first input, it does not allow me to perform the second input. I'm new to java and I have read the chapter on file inputs, repeatedly. However I still don't see why this error is occurring.
The two String variables(pword, uname) where created outside of this section of code and the FileWriter and PrintWriter classes need to append data to a file is also present outside the loop as well. Do i need to open and close the file before and after each input? that seems excessive.
for (index = 0; index <= arraylength; index ++)
{
System.out.println("Enter a username..");
uname = keyboard.nextLine();
outputFile.println(uname);
System.out.println("Enter a password..");
pword = keyboard.nextLine();
outputFile.println(pword);
}
this is the full program, updated with the suggestions to use "keyboard.next();"
instead of "keyboard.nextLine();"
in my IDE i still get the error to my console
Enter a username..
Enter a password..
when i want it to ask for the username, then take my input, then ask for the password.
import java.util.Scanner;
import java.io.*;
public class Register {
public static void main (String [] args) throws IOException
{
int index ;
int arraylength;
String uname, pword;
Scanner keyboard = new Scanner(System.in);
//create users
System.out.println("How many users would you like to create");
arraylength = keyboard.nextInt();
/*
create a filewriter object, name the registration database, and
create the file using the name of the database.
Pass the filewriter object to the print writer object as an arg
*/
FileWriter fwriter = new FileWriter("database.txt", true);
PrintWriter outputFile = new PrintWriter (fwriter); //constructor
//loop user creation
for (index = 0; index <= arraylength; index ++)
{
keyboard = new Scanner(System.in);
System.out.println("Enter a username..");
uname = keyboard.next(); // create string object
outputFile.println(uname);
keyboard = new Scanner(System.in);
System.out.println("Enter a password..");
pword = keyboard.next();
outputFile.println(pword);
//creat the new file with filewriter so the file is not erased
//write to the new file with printwriter object
}
outputFile.close();
}
}
You can use java.util.Scanner for reading the data from standard input
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username..");
uname = scan.next();
This will wait until you press Enter key. Hope it will help you
I like to use BufferedWriter more than PrintWriter and its working with the BufferedWriter:
int index;
int arraylength;
String uname, pword;
Scanner keyboard = new Scanner(System.in);
// create users
System.out.println("How many users would you like to create");
arraylength = keyboard.nextInt();
/*
* create a filewriter object, name the registration database, and
* create the file using the name of the database.
*
* Pass the filewriter object to the print writer object as an arg
*/
BufferedWriter bw = new BufferedWriter(new FileWriter(
"full file path goes here",true));
// loop user creation
for (index = 1; index <= arraylength; index++) {
keyboard = new Scanner(System.in);
System.out.println("Enter a username..");
uname = keyboard.next(); // create string object
bw.write(uname);
keyboard = new Scanner(System.in);
System.out.println("Enter a password..");
pword = keyboard.next();
bw.write(pword);
bw.newLine();
}
bw.close();
this should give you the desired behavior

appending to arrays won't work for my code, is there a bug somewhere or am I using it wrongly?

The program I'm working on is supposed to append values input from a scanner to their respective arrays from a different method. However when using the code exampleArray.push(value);, it gives me an errors saying :" Error: cannot find symbol, symbol: method push(java.lang.String)."
Am I doing anything wrong? Did I miss something?
Code for the class:
public class Agenda
{
public static String names[];
public static int days[];
public static int types[];
public static int diffs[];
public static int row;
public Agenda()
{
}
public void createA() throws IOException
{
FileWriter nFile = new FileWriter("CurrentAgenda.txt", false);
PrintWriter output = new PrintWriter(nFile, false);
output.println("Current Agenda");
//clear out data file
output.close();
nFile.close();
FileWriter dFile = new FileWriter("Data.txt", false);
PrintWriter clear = new PrintWriter(dFile, false);
clear.print("");
clear.close();
dFile.close();
create();
}
public static void create() throws IOException
{
System.out.println("Your file will be: CurrentAgenda.txt");
System.out.println("Input types:");
System.out.println("Name--> Characters: A-Z");
System.out.println("Type/Summative=(3), Formative=(2), Extra=(1)--> Integer: 1-3");
System.out.println("Days Until Deadline--> Integer: Any");
System.out.println("Difficulty/Easy=(1), Medium=(2), Hard=(3)--> Integer: 1-3");
System.out.println("Please input assignments:\n");
String again;
names = new String[100];
days = new int[100];
types = new int[100];
diffs = new int[100];
row=0;
do{
FileWriter data = new FileWriter("Data.txt", true); //putting data in table for append
PrintWriter append = new PrintWriter(data, true);
Scanner input = new Scanner(System.in);
System.out.println("Please input assignment name: ");
String name = input.nextLine();
names[row] = name;
append.print(name +",");
System.out.println("Please input the number of days until the due date: ");
int day = input.nextInt();
days[row] = day;
append.print(day + ",");
System.out.println("Please input assignment type:");
int type = input.nextInt();
types[row] = type;
append.print(type + ",");
System.out.println("Please input the assignment difficulty: ");
int diff = input.nextInt();
diffs[row] = diff;
append.println(diff);
append.close();
data.close();
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
again = input.next();
input.close();
row++;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work.add(new Items((names[count]),(days[count]),(types[count]),(diffs[count])));
}
Collections.sort(work, new Comp1());
FileWriter firstL = new FileWriter("CurrentAgenda.txt", true); //formats the Viewer file
PrintWriter paste = new PrintWriter(firstL, true);
paste.println("Do these Assignments in order:");
paste.close();
firstL.close();
System.out.println("Sorted Assignment Entries: ");
for(Items e:work)
{
FileWriter agenda = new FileWriter("CurrentAgenda.txt", true);
PrintWriter add = new PrintWriter(agenda, true);
add.println(e);
add.close();
agenda.close();
System.out.println(e);
}
}
public static void add() throws IOException
{
String again;
do{
FileWriter data = new FileWriter("Data.txt", true);
PrintWriter append = new PrintWriter(data, true);
Scanner input = new Scanner(System.in);
System.out.println("Please input assignment name: ");
String name = input.nextLine();
names.push(name);
append.print(name +",");
System.out.println("Please input the number of days until the due date: ");
int day = input.nextInt();
days.push(day);
append.print(day + ",");
System.out.println("Please input assignment type:");
int type = input.nextInt();
types.push(type);
append.print(type + ",");
System.out.println("Please input the assignment difficulty: ");
int diff = input.nextInt();
diffs.push(diff);
append.println(diff);
append.close();
data.close();
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
again = input.next();
++row;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work2 = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work2.add(new Items((names[count]),(days[count]),(types[count]),(diffs[count])));
}
Collections.sort(work2, new Comp1());
FileWriter firstL = new FileWriter("CurrentAgenda.txt", false);
PrintWriter paste = new PrintWriter(firstL, false);
paste.println("Current Agenda");
paste.println("Do these Assignments in order:");
paste.close();
firstL.close();
System.out.println("Sorted Assignment Entries: ");
for(Items e:work2)
{
FileWriter agenda = new FileWriter("CurrentAgenda.txt", true);
PrintWriter add = new PrintWriter(agenda, true);
add.println(e);
add.close();
agenda.close();
System.out.println(e);
}
}
There is not push method for java arrays. Instead, you must set the value by using the index at which you want to set it. For example, you could set the first spot of the names array to Rob by saying:names[0]="Rob"; You will have to know the index. For your situation, you can consider using a counter that starts at 0 and increments every time you save an assignment name.
Hope this helps!
You should not be using standard arrays. Your compiler is correct there is no push method for a standard array.
But there is a different array-like type you can use.
Try using an ArrayDeque (documentation here). It has the push method you're looking for.
You just have to remember that they get initialized a little differently than an array.
Instead of
String[] array = new String[50];
You use
ArrayDeque<String> array = new ArrayDeque<>(50);
The capacity argument for the constructor is optional. The size of an ArrayDeque can change, unlike a standard array.
You can then call your push(E) method just like you do in your code.
A push() method does not exist for arrays, if you want you can make a generic metod to push to your array something like:
<T> void push(T[] array, int index, T value) {
array[index] = value;
}

get input from user and store it in String Array in Java

i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}

Scanner throws InputMismatchException with null

import java.io.*;
import java.util.*;
public class Main{
public static void main(String [] args) throws InputMismatchException{
double width;
int period;
double Ppp;
Scanner in0 = new Scanner(System.in);
Scanner in1 = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
System.out.println("Give width\n");
while(in0.hasNextDouble()){
width = in0.nextDouble();
}
in0.close();
System.out.println("\n");
System.out.println("Give period");
while(in1.hasNextInt()){
period = in1.nextInt();
}
in1.close();
System.out.println("\n");
System.out.println("Insert width peak to peak");
while(in2.hasNextDouble()){
Ppp = in2.nextDouble();
}
in2.close();
}
I run this code block
I insert the first input but it displays null for each input
and then it crash
May someone run it and tell if he has the same problem
I use BlueJ compiler
The cause of the problem is this
Scanner in0 = new Scanner(System.in);
Scanner in1 = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
and this
in0.close();
...
in1.close();
...
in2.close();
When you create the Scanner, you work on System.in, then you close it. This cause that next Scanner operate on closed stream.
The solution is to create a single Scanner for InputStream.
Scanner scanner = new Scanner(System.in);
System.out.println("Give width\n");
double width = scanner.nextDouble();
System.out.println("Give period");
int period = scanner.nextInt();
System.out.println("\nInsert width peak to peak:");
double p2p = scanner.nextDouble();
This is only example that do not validate the user input.
public static void main(String [] args) throws InputMismatchException{
double width;
int period;
double Ppp;
Scanner in0 = new Scanner(System.in);
System.out.println("Give width\n");
// This will read the line, and parse the result as a double, this way you can insert a number and press enter
width = Double.parseDouble(in0.nextLine());
System.out.println("Give period");
period = Integer.parseInt(in0.nextLine());
System.out.println("\n");
System.out.println("Insert width peak to peak:");
ppp = Double.parseDouble(in0.nextLine());
in0.close();
}

Categories

Resources