I'm trying to grab 3 strings from the user.
The issue I'm running into at the moment is that the scanner never ends/never stores the first user input value? With the limited amount of research I've done so far it appears that the scanner method has some intricacies that lie far beyond the cover.
My current code is below, followed by the complete method. Any sort of explanation would be highly appreciated. Thank you!
Code pertaining to question:
//prompt user for array values by row
System.out.println("Enter matrix values by row: ");
userInput[0] = in.nextLine();
userInput[1] = in.nextLine();
userInput[2] = in.nextLine();
Complete method:
public static double[][] setArray()
{
//initiate variables
String stringValue = "";
double doubleValue = 0;
//instantiate string array for user input values
String[] userInput = new String[3];
//instantiate return array
double[][] array = new double[3][4];
//prompt user for array values by row
System.out.println("Enter matrix values by row: ");
userInput[0] = in.nextLine();
userInput[1] = in.nextLine();
userInput[2] = in.nextLine();
//stop each scanner
int valueCounter = 0;
for(int eachString = 0; eachString < 3; eachString++)
{
for(int index = 0; index < userInput[eachString].length(); index++)
{
//exception handling
//if string does not contain a space, period, or valid digit
while(userInput[eachString].charAt(index) != ' '
&& userInput[eachString].charAt(index) < '0'
&& userInput[eachString].charAt(index) > '9'
&& userInput[eachString].charAt(index) != '.')
{
System.out.println("Invalid input. Digits must be in integer"
+ " or double form. (i.e. 4 5.0 2.3 9)");
System.out.println("Re-enter given matrix value");
userInput[eachString] = in.nextLine();
}
}
//given string is valid at this point//
//for each index in string value
for(int eachIndex = 0; eachIndex < userInput[eachString].length(); eachIndex++)
{
//while value != ' '... += string... if value == ' ' stop loop
while(userInput[eachString].charAt(eachIndex) != ' ')
{
stringValue += userInput[eachString].charAt(eachIndex);
}
doubleValue = Double.valueOf(stringValue);
array[eachString][valueCounter] = doubleValue;
valueCounter++;//array[0-2][0-3 (valueCounter)]
stringValue = "";//clear string
}
}
return array;
}
You would just want to break up the scanner to read 1 number at a time and then ask for the second number and then read it in and then ask for the third number.
Or you could have them provide the 3 numbers divided by a space or something and read it in as a string and split the string per each space and parse to each userInput.
I would so the latter, it would look something like this:
System.out.println("Enter matrix values by row: ");
String temp = in.nextLine();
String[] tempArray = temp.split("\\s+");
userInput[0] = tempArray[0];
userInput[1] = tempArray[1];
userInput[2] = tempArray[2];
Obviously error checking needs to happen. But this should work for you.
Related
I am trying to solve a competitive programming practice set. I am only a beginner so please bear with me.
Here is the problem
The history teacher at your school needs help in grading a True/False test using his designed
scoring technique. Each correct answer is awarded two points, each wrong answer gets one
point deducted, and no answer gets a zero.
Your task is to help the teacher automate this task.
Input
The first entry in the file contains answers to the test in the form:
TFFTFTFTFFFTTTTFTFTF
The next line is the number test cases, i.e. number of students who took the test.
Every other entry in the file is the student ID, followed by a blank, followed by the student's
responses. For example, the entry:
S2013-1-1003 TFTFTFTT TFTFTFFTTFT
indicates that the student ID is S2013-1-1003 and the answer to question 1 is True, the
answer to question 2 is False, and so on. This student did not answer question 9. The exam, in
this example, has 20 questions.
Output
The output should be the student's ID, followed by the answers, followed by the test score,
followed by the test grade. Assume the following grade scale: 90%-100%, A; 80%-89.99%, B;
70%-79.99%, C; 60%-69.99%, D; and 0%-59.99%, F.
Sample Input
TTTTTFFFFF
3
S2013-1-2345 TTTTTFFFFF
S2013-1-1266 TFTFTFTFTF
S2012-2-0006 T T TF F F
Sample Output
S2013-1-2345 TTTTTFFFFF 20 A
S2013-1-1266 TFTFTFTFTF 8 F
S2012-2-0006 T T TF F F 12 D
*/
My code :
public class Score {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//input answer to the test
String correctAnswer = sc.nextLine();
//input number of test cases
int numberOfStudents = sc.nextInt();
String studentID[] = new String[numberOfStudents];
String studentAnswer[] = new String[numberOfStudents];
int studentScore[] = new int[numberOfStudents];
char studentGrade[] = new char[numberOfStudents];
//ask user to input data
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
//checks whether the student has the correct score
for(int y = 0; y < correctAnswer.length(); y++) {
if(studentAnswer[y].charAt(y) == correctAnswer.charAt(y)) {
studentScore[y]++;
}//end of if
}//end of for
for(int y = 0; y < numberOfStudents; y ++) {
double percentage = (studentScore[y] / correctAnswer.length()) * 100 ;
//check the letter grade of the student
if(percentage >= 90) {
studentGrade[y] = 'A';
}//end of first if
else if(percentage >= 80 && percentage <= 89) {
studentGrade[y] = 'B';
}//end first else if
else if(percentage >= 70 && percentage <= 79) {
studentGrade[y] = 'C';
}//end of second else if
else if(percentage >= 60 && percentage <= 69) {
studentGrade[y] = 'D';
}//end of third else if
else {
studentGrade[y] = 'F';
}//end of last else
}//end of for
//close the scanner to avoid any memory leaks
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%d\t%d\t%d\t%d", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i]);
}//end of first for
}//end of main
}//end of class
The program compiles and all however once I input my test data, i received an outofBounders error from my compiler. Then I realized that I had made a mistake in this code
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
if StudentID and studentAnswer is an integer then I can seperate them by using space and enter my data in one line. However I forgot that when I use space as a seperator, it is not seperated as space is still considered a string. My main question here is how do I ask the user to input his student ID and his answer in one line seperated by a string so that I can store then into my arrays such as studentID array and studentAnswer array.
The format specifier that you use for display the score is wrong! you can can change it as below:
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%s\t%s\t%d\t%s", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i])
}//end of first for
You are taking input using sc.nextLine(). What does nextLine() do is, it reads all character from input buffer until \n or newline character is found.
So you can ask user to give input something like this way:
StudentID \n studentAnswer
Another way you can modify your input taking array as like as this:
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
String line = sc.nextLine();
char[] chars = line.toCharArray();
String fs = "";
String sc = "";
boolean flag = false;
for(int j=0;j<chars.length;j++){
if(chars[j]==' ') {
flag = true;
continue;
}
if(flag ==false) fs += chars[j];
else sc += chars[j];
}
studentID[i] = fs;
studentAnswer[i] = sc;
}
Write a program that takes a string input from the user and then outputs the first character, then the first two, then the first three, etc until it prints the entire word. After going down to one letter, print the opposite back up to the full word.
I've gotten the first part done.
Scanner word = new Scanner(System.in);
System.out.println("Enter a word.");
String thing = word.next();
String rest = "";
for(int i=0;i< thing.length();i++){
String w = thing.substring(i,i+1);
rest += w;
System.out.println(rest);
}
This is what it should look like.
C
Co
Com
Comp
Compu
Comput
Compute
Computer
Computer
Compute
Comput
Compu
Comp
Com
Co
C
Strings in Java are indexed starting from 0, so the last character is indexed at length-1.
To iterate from the last character down to the first, the for loop would be for(int i = thing.length () - 1; i >= 0; i--).
Alternatively, recursion would be a simpler solution considering you already obtained the strings that should be printed in reverse.
static void f (String str, int n) {
if (n > str.length ()) return;
String temp = str.substring (0, n); // obtain the string
System.out.println (temp); // print
f (str, n + 1); // go to next substring
System.out.println (temp); // print after returning from the last obtainable substring
}
The function can now be called via f(thing, n);
You can try to implement two arrays, in the first you must split the String entered from the Scanner and in the second you must store the generated aux variable in each iteration of the first array, To finish you must iterate the second array in reverse.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = sc.next();
String[] array = word.split("");
int length = array.length;
String[] auxArray = new String[length];
String aux = "";
for (int i = 0; i < length; i++) {
aux += array[i];
auxArray[i] = aux;
System.out.println(aux);
}
for (int i = length - 1; i >= 0; i--) {
System.out.println(auxArray[i]);
}
}
I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>
For example, the user enters "1 2 3 4", how do I extract those four numbers and put them into separate spots in an array?
I'm just a beginner so please excuse my lack of knowledge.
for (int i = 0; i < students; i++) {
scanner.nextLine();
tempScores[i] = scanner.nextLine();
tempScores[i] = tempScores[i] + " ";
tempNum = "";
int scoreCount = 0;
for (int a = 0; a < tempScores[i].length(); a++) {
System.out.println("Scorecount " + scoreCount + " a " + a );
if (tempScores[i].charAt(a) != ' ') {
tempNum = tempNum + tempScores[i].charAt(a);
} else if (tempScores[i].charAt(a) == ' ') {
scores[scoreCount] = Integer.valueOf(tempNum);
tempNum = "";
scoreCount ++;
}
}
You can use String.split(String) which takes a regular expression, \\s+ matches one or more white space characters. Then you can use Integer.parseInt(String) to parse the String(s) to int(s). Finally, you can use Arrays.toString(int[]) to display your int[]. Something like
String line = "1 2 3 4";
String[] tokens = line.split("\\s+");
int[] values = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
values[i] = Integer.parseInt(tokens[i]);
}
System.out.println(Arrays.toString(values));
Outputs
[1, 2, 3, 4]
If you are very sure that the numbers will be separated by space then you could just use the split() method in String like below and parse individually :
String input = sc.nextLine(); (Use an sc.hasNextLine() check first)
if (input != null || !input.trim().isEmpty()) {
String [] numStrings = input.split(" ");
// convert the numbers as String to actually numbers by using
Integer.parseInt(String num) method.
}
I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Try this
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.
String input = scanner.nextLine(); // get the entire line after the prompt
String[] numbers = input.split(" "); // split by spaces
Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()
Scanner has a method called hasNext():
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
System.out.println(scanner.nextInt());
}
If you know how much integers you will get, then you can use nextInt() method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.
import java.util.Scanner; // imports class so we can use Scanner object
public class Test
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter numbers: ");
// This inputs the numbers and stores as one whole string value
// (e.g. if user entered 1 2 3, input = "1 2 3").
String input = keyboard.nextLine();
// This splits up the string every at every space and stores these
// values in an array called numbersStr. (e.g. if the input variable is
// "1 2 3", numbersStr would be {"1", "2", "3"} )
String[] numbersStr = input.split(" ");
// This makes an int[] array the same length as our string array
// called numbers. This is how we will store each number as an integer
// instead of a string when we have the values.
int[] numbers = new int[ numbersStr.length ];
// Starts a for loop which iterates through the whole array of the
// numbers as strings.
for ( int i = 0; i < numbersStr.length; i++ )
{
// Turns every value in the numbersStr array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt( numbersStr[i] );
// OPTIONAL: Prints out each value in the numbers array.
System.out.print( numbers[i] + ", " );
}
System.out.println();
}
}
There is more than one way to do that but simple one is using String.split(" ")
this is a method of String class that separate words by a spacial character(s) like " " (space)
All we need to do is save this word in an Array of Strings.
Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :
for (int i = 0; i < stringsArray.length; i++) {
int x = Integer.parseInt(stringsArray[i]);
// Do what you want to do with these int value here
}
Best way is converting the whole stringArray to an intArray :
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
now do any proses you want like print or sum or... on intArray
The whole code will be like this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
}
}
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
Using this on many coding sites:
CASE 1: WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8 , 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
It's working with this code:
Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();
A simple solution can be to consider the input as an array.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //declare number of integers you will take as input
int[] arr = new int[n]; //declare array
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt(); //take values
}
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
This method only requires users to enter the "return" key once after they have finished entering numbers:
It also skips special characters so that the final array will only contains integers
ArrayList<Integer> nums = new ArrayList<>();
// User input
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
if (!n.isEmpty()) {
String[] str = n.split(" ");
for (String s : str) {
try {
nums.add(Integer.valueOf(s));
} catch (NumberFormatException e) {
System.out.println(s + " cannot be converted to Integer, skipping...");
}
}
}
//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenSum = 0;
int oddSum = 0;
while (n > 0) {
int last = n % 10;
if (last % 2 == 0) {
evenSum += last;
} else {
oddSum += last;
}
n = n / 10;
}
System.out.println(evenSum + " " + oddSum);
}
}
if ur getting nzec error, try this:
try{
//your code
}
catch(Exception e){
return;
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`