I was trying to store input as
5
3DRP 3QEW
8AQW 9ADA
I want to read that input in as a copy paste and put it. I've tried this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userNumber;
userNumber = scan.nextLine();
String[] tokens = userNumber.split("[ ]");
System.out.println(tokens[1]);
for(int i = 0; i < tokens.length;i++) {
System.out.println(tokens[i]);
}
scan.close();
}
My goal is to basically read that input in as a copy paste into the IDE or through a file a .txt and then store every single character besides whitespaces into a char array that is 1d or 2d.
From what I understand, you want to read 3 lines from the console, remove all the white spaces from that text and store it as a char array.
If that is the case, here is how you could do that:
int numberOfLinesToRead = 3;
try(Scanner sc = new Scanner(System.in)){
StringBuilder buff = new StringBuilder();
while(numberOfLinesToRead-- > 0){
String line = sc.nextLine();
String noSpaces = line.replaceAll("\\s", "");
buff.append(noSpaces);
}
char[] characters = buff.toString().toCharArray();
System.out.println(Arrays.toString(characters));
}catch (Exception e) {
e.printStackTrace();
}
Related
I'm write a code that pulls a word from a file and guesses it. For instance the word would be "apple".
The user will see: *****
If they input 'p' as a guess they see: *pp**
So far it's working if I manually the word apple in a variable called secretPhrase, however I'm not sure how to have the program pull the word from a text file and store it into secretPhrase for the user to guess.
public static void main(String args[]) {
String secretPhrase = "apple";
String guesses = " ";
Scanner keyboard = new Scanner(System.in);
boolean notDone = true;
Scanner word = new Scanner(System.in);
System.out.print("Enter a word: ");
while(true) {
notDone = false;
for(char secretLetter : secretPhrase.toCharArray()) {
if(guesses.indexOf(secretLetter) == -1) {
System.out.print('*');
notDone = true;
} else {
System.out.print(secretLetter);
}
}
if(!notDone) {
break;
}
System.out.print("\nEnter your letter:");
String letter = keyboard.next();
guesses += letter;
}
System.out.println("Congrats");
}
You have several options. One is to do the following. It is not complete and doesn't check on border cases. But you can figure that out. It presumes the file contains one word per line.
try {
RandomAccessFile raf = new RandomAccessFile(
new File("wordfile.txt"), "r");
Random r = new Random();
// ensure the length is an int
int len = (int)(raf.length()&0x7FFFFFFF);
// randomly select a location
long loc = r.nextInt(len);
// go to that file location
raf.seek(loc);
// find start of next line
byte c = raf.readByte();
while((char)c != '\n') {
c = raf.readByte();
}
// read the line
String line = raf.readLine();
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}
A much easier solution for perhaps a smaller set of words is to just read them into a List<String> and the do a Collections.shuffle() to randomize them. Then just use them in the shuffled order.
I'm trying to make a code that reads a text file, and stores every line into an Array, heres my code:
import java.util.Scanner;
import java.io.File;
public class JavaPractice
{
public static void main (String[] args) throws Exception
{
File file = new File("C:/Users/Andrew/Desktop/textFile.txt");
Scanner fileScanner = new Scanner(file);
int x = 1;
while (fileScanner.hasNextLine())
{
fileScanner.nextLine();
x++;
}
String names[] = new String[x];
Scanner reader = new Scanner(file);
while (reader.hasNextLine())
{
names[x] = reader.nextLine();
System.out.println(names[x]);
x--;
}
System.out.println(names[0]);
fileScanner.close();
reader.close();
}
}
What i'm going for is to get fileScanner to read how many lines my file has, store that into X, and then make an array with X number of values, and then start storing my values into the array.
The problem is in your array declaration and the way you access array in while loop,
String names[] = new String[x];
Scanner reader = new Scanner(file);
while (reader.hasNextLine())
{
names[x] = reader.nextLine();
System.out.println(names[x]);
x--;
}
You are declaring array of size x,
String names[] = new String[x];
and in while loop you are accessing like this,
names[x] = reader.nextLine();
Which will run into ArrayIndexOutOfBounds exception, as you can only access from 0 to x-1 elements in an array,
You should try making it this,
names[x-1] = reader.nextLine();
System.out.println(names[x-1]);
Also, you should declare your x = 0 instead of x = 1; So your lines are counted correctly.
I have a text file with the following line define : Hi 0x01. I'm trying to read in the word Hi and store it in its own variables and 0x01 in its own variable.The problem I'm having is that i seem to be able to read in Hi, but i cant read in0x01`.Here is my code
File comms =new File("src/Resources/com.txt");
try (Scanner scan = new Scanner(comms)) {
while (scan.hasNext()) {
String line = scan.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter("\\s+");
try {
String comm1 = sc.next();
// System.out.println(comm1);
int value =sc.nextInt();
System.out.println(value);
sc.close();
} catch (Exception ef){
}
I honestly have no idea what you're trying to do here. You'd better scan it once:
File comms = new File("src/Resources/com.txt");
try(Scanner scan = new Scanner(comms)) {
while(scan.hasNext()) {
String line = scan.nextLine();
String[] words = line.split(" ");
System.out.println(words[0]); // "Hi"
System.out.println(words[1]); // "0x01"
}
}
catch(Exception e) {
}
Now, having these in separate strings you can do anything in the world with it like converting words[1] to int.
i need to read multiple lines from stdin in java.
For example i need to read this two lines:
A A A H
A E D A H
and give an answer for each line.
I have made this but i can stop the while
Scanner sc = new Scanner(System.in);
Posicao p;
int max[][] = new int[4][], j = 0;
String com;
String[] b;
char[] c;
while(sc.hasNextLine()){
p = new Posicao();
com = sc.nextLine();
b = com.split(" ");
c = new char [b.length];
for(int i = 0;i<b.length;i++) c[i] = b[i].charAt(0);
p.comando(c);
max[j++] = p.retorna();
}
if (com.isEmpty()) {
break;
}
You could check what the user inputs and exit on empty input or the word "exit":
/*This would go in your while loop, after you process the input*/
if (com.equals("") | com.equals("exit")) {
System.out.println("Exiting...");
break;
} else
System.out.println("Still in loop");
Ideally you need to modify this part while(sc.hasNextLine()) to break the loop. Do you know any of the below values?
Number of lines
Any special char using which you can find end of input
Read each line using Scanner.nextLine() method and use String.split() or StringTokenizer to read tokens from each line. (see the example below) :
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine())
{
String[] tokens = scanner.nextLine().split("\\s");
System.out.println(Arrays.toString(tokens));
}
scanner.close();}
I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}