Scanner cannot read input - java

package algo.chapter1.Ex1_1_33;
import java.util.Scanner;
import edu.princeton.cs.introcs.StdIn;
import edu.princeton.cs.introcs.StdOut;
public class MatrixClient
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
while(true)
{
switch (getInput())
{
case 1:
//Dot Product
performDotProduct();
break;
case 2:
performMatrixProduct();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
StdOut.println("Thank You!");
System.exit(0);
break;
default:
StdOut.println("Invalid Choice!!!");
}
}
}
public static int getInput()
{
StdOut.println("******************************");
StdOut.println("1.Dot Product");
StdOut.println("2.Matrix-Matrix product");
StdOut.println("3.Transpose");
StdOut.println("4.Matrix-Vector Product");
StdOut.println("5.Vector-Matrix product");
StdOut.println("6.Exit");
StdOut.println("******************************");
StdOut.print("\nChoose one from the above: ");
return StdIn.readInt();
}
public static void performDotProduct()
{
StdOut.print("Enter elements of vector A: ");
double[] A = readVector();
StdOut.print("Enter elements of vector B: ");
double[] B = readVector();
StdOut.println("The dot product is: " + Matrix.dot(A, B));
}
public static void performMatrixProduct()
{
StdOut.print("Enter the size of matrix A: ");
int size = scan.nextInt();
double[][] A = readMatrix(size);
for (double[] row : A)
{
for (double item : row)
StdOut.print(item + "\t");
StdOut.println();
}
}
public static double[] readVector()
{
String[] input = scan.nextLine().split(" ");
double[] x = new double[input.length];
for (int i = 0; i < input.length; i++)
x[i] = Double.parseDouble(input[i]);
return x;
}
public static double[][] readMatrix(int N)
{
int counter = 0;
double[][] matrix = new double[N][N];
while (counter < N)
{
StdOut.print("Enter elements of row " + (counter + 1) + ": ");
matrix[counter] = readVector();
counter++;
}
return matrix;
}
}
I'm using readVector() method to read a row of doubles and return a double array. When it is used for dot product, input is being read returned fine, but when I use matrix-matrix multiplication option, readVector() doesn't wait for input. It throws NumberFormatExcpetion: empty string.
I don't understand why readVector() behaves differently.

The problem is in this line:
int size = scan.nextInt();
When your code asks to enter the size of the matrix, you enter a number, and then hit enter. The above code, however, only reads the number that you enter. It does not consume the enter (\n character).
After your code consume the matrix size, your code does:
String[] input = scan.nextLine().split(" ");
which consumes the enter (\n character), and then split it by space. This (scan.nextLine()), of course, returns an empty string.
To fix it, instead of using:
int size = scan.nextInt();
use:
int size = scan.nextInt();
scan.nextLine();

In your code change:
int size = scan.nextInt();
To
int size = scan.nextInt();
scan.nextLine();

Related

Finding the largest, second largest, second smallest, and smallest int from an array in java

I'm using a method to print the largest, second largest, smallest, and second smallest integers. This is what I have so far for the base:
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
This is the method being called so far:
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
The actual output is to formatted like
(largest,secondlargest),(smallest,secondsmallest)
I've never used an array before, and I'm not sure how to use loops with it to find the values. How do I begin this?
Here is the complete code for my program. You can disregard the second and third case, however, I still need help with the third. I need to display all prime numbers in order. Here is the requirement: Twin Prime Numbers: This should let the user specify a limit n (I used limit instead) (if n is 1000, then consider 1
to 1000), and lists the pairs of twin primes up to n. The sample run is (3,5),(5,7),(11,13),(17,19)
The complete code:
import java.util.Scanner;
public class PatternChecker{
// The scanner is accessible for every method included
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int limit;
System.out.println("List of Pattern Checker problems:\n1) Largest and Smallest Pairs\n2) Patterns of Triangles\n3) Twin Prime Pairs\n4) Quit");
System.out.print("Choice: ");
int choice = input.nextInt();
// The switch statement for the variable "choice" and each case
switch (choice) {
default:
System.out.println("\n*** INVALID OPTION");
break;
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
case 2:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(triangleOne(limit));
System.out.println(triangleTwo(limit));
System.out.println(triangleThree(limit));
System.out.println(triangleFour(limit));
break;
case 3:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(primePairs(limit));
break;
case 4:
System.out.println("\n*** End");
break;
}
}
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle One)
public static String triangleOne(int limit) {
System.out.println("*** Patterns of Triangles");
for (int x = 1; x <= limit; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Two)
public static String triangleTwo(int limit) {
for (int x = limit; x > 0; x--) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Three)
public static String triangleThree(int limit) {
for (int row = 1; row <= limit; row++) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = row; num > 0; num--) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Four)
public static String triangleFour(int limit) {
for (int row = limit; row >= 0; row--) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = 1; num <= row; num++) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 3 Method: Twin Prime Pairs
public static String primePairs(int limit) {
System.out.println("*** Twin Prime Numbers up to " + limit);
return "";
}
}
Ok based on the comment i have written a quick answer with arraylists. hope this helps.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MaxMin {
private List<Integer> alist = new ArrayList<Integer>();
public static void main(String args[]) {
MaxMin maxmin = new MaxMin();
maxmin.init();
}
public void init() {
System.out.println("Welcome!!!");
readFromUser();
printUserList();
doSort();
display();
}
public void readFromUser() {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Enter the total number of elements :");
Integer totalElements = scanner.nextInt();
for (int i=0;i<totalElements;i++) {
System.out.print("Enter the " + i +" number");
alist.add(scanner.nextInt());
}
}catch(Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
public void printUserList() {
System.out.println("user entered list is :");
System.out.println(alist);
}
public void doSort() {
Collections.sort(alist);
}
public void display() {
System.out.println("(" +alist.get(alist.size()-1)+ "," +alist.get(alist.size()-2)+ ")" + "(" +alist.get(0)+"," +alist.get(1) +")");
}
}
I hope this isn't a homework problem, but the idea is to use a loop with the array, and keep track of the largest and smallest numbers.
Start with assigning the smallest number variable to Integer.MAX_VALUE, so the first number you check will be assigned to the smallest number, because all integer values except 2^31 - 1 are smaller than Integer.MAX_VALUE, and you do that for biggest too, but with Integer.MIN_VALUE.
And then whenever you assign the biggest number again, you assign the secondBiggest variable to the "biggest" variable.
With that in mind, you just need to loop through the values of the array and check if they're larger than the biggest (in which you re-assign it) or smaller than the smallest(same thing as biggest).
int[] array = new int[]{5, 3, 4, 1, 2};
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
^
Example of looping through an array
I created an example for you.
First of all it generates a list of prime numbers till the limit (in this case hardcoded 100). Next it asks for all prime pairs and prints them. The pairs are stored in an ArrayList so it is very easy to get the first and the last pair.
It's not realy hard to understand so I don't know what to explain. Take a look at the code and if you have any questions feel free to ask.
import java.util.ArrayList;
public class PatternChecker {
public ArrayList<Integer> primes = new ArrayList<>();
public static void main(String[] args) {
PatternChecker pc = new PatternChecker();
pc.detectPrimes(100);
ArrayList<int[]> numbers = pc.getPairs();
System.out.println("Print all pairs: ");
numbers.stream().forEach((intA)->System.out.println(intA[0]+" / "+intA[1]));
System.out.println("Print just the greatest and the smallest pair: ");
System.out.println("("+numbers.get(0)[0]+","+numbers.get(0)[1]+")");
System.out.println("("+numbers.get(numbers.size()-1)[0]+","+numbers.get(numbers.size()-1)[1]+")");
}
public void detectPrimes(int limit) {
for(int i=2;i<limit;i++)
if(isPrime(i))
primes.add(i);
}
protected boolean isPrime(int no) {
for(int i=0;i<primes.size();i++)
if(no % primes.get(i) == 0) return false;
return true;
}
public ArrayList<int[]> getPairs() {
ArrayList<int[]> result = new ArrayList<>();
int last = primes.get(0);
for(int i=1;i<primes.size();i++) {
if(primes.get(i)==last+2) {
int[] resH = new int[2];
resH[0] = last;
resH[1] = primes.get(i);
result.add(resH);
}
last = primes.get(i);
}
return result;
}
}

Java - Looping through ArrayList to scan for matching value [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 6 years ago.
I'm trying to write a simple program using an ArrayList that adds values, removes values, and prints values. However, I'm having an issue with removing values that the user inputs. The user should input a designated amount of values (determined by the user) and then the program should remove those values (if there are duplicates then it should just remove the first instance of the number which is fine). It's not removing the values and in some cases removes one value. I'm a bit confused as to where my code is bugged. Here is my code for remove values:
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
And here is my full code:
public class Main {
private static ArrayList<Integer> arrayList = new ArrayList<Integer>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
printOptions();
int option = scanner.nextInt();
while (option != 0) {
switch(option) {
case 1:
addVals();
printOptions();
option = scanner.nextInt();
break;
case 2:
removeVals();
printOptions();
option = scanner.nextInt();
break;
case 3:
printVals();
printOptions();
option = scanner.nextInt();
break;
case 4:
printOptions();
printOptions();
option = scanner.nextInt();
break;
default:
System.out.println("Not a valid option, please enter again:");
option = scanner.nextInt();
break;
}
}
}
private static void addVals() {
System.out.println("How many values would you like to add?");
int amountToAdd = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToAdd + " values:");
for(int i = 0; i < amountToAdd; i++) {
int vals = scanner.nextInt();
arrayList.add(vals);
}
}
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
private static void printVals() {
for(int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + " ");
}
System.out.println();
}
private static void printOptions() {
System.out.println();
System.out.println("Program options: ");
System.out.println("1. Add values\n2. Remove values\n3. Print values\n4. Print options\n0. Exit\n");
System.out.println("\nWhat would you like to do? (enter an option):");
}
}
arrayList.remove(i) removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
that is the bug your code
for more details refer below link
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int) ,

How do I output a TABLE with names and scores with only using Arrays and Methods?

I have been trying to find the answer to this question but to no avail!
Basically I have to write a program where 'x' number of players can enter a guessing game and input their guesses and then get a score.
However, right after they input their guesses, i have to output it in a table form like this "NAME GUESS SCORE"
I do not know how i can do this with a for loop since a for loop println can only print values from playersArray. How can I print another array like guessesArray to the side of it?
I can only use Arrays and Methods to do this.
Below I will show u what i have right now:
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class game
{
static int[] guessesArray;
static int guess;
static String [] playersArray;
static int[] currscoresArray;
static int [] addscoresArray;
static int [] finalscoresArray;
public static void main(String [] args){
System.out.print("Number of players? ");
Scanner kb = new Scanner(System.in);
int numplayers = kb.nextInt();
//Initialize
playersArray = new String[numplayers];
guessesArray = new int [numplayers];
currscoresArray = new int [numplayers];
addscoresArray = new int [numplayers];
finalscoresArray = new int [numplayers];
populateArray(playersArray);
displayMenu();
}
public static void populateArray( String[] x){
Scanner kb = new Scanner(System.in);
for (int i = 0; i<x.length ; i++){
System.out.print("Enter Player "+(i+1)+": ");
x[i]=kb.nextLine();
}
}
public static void displayMenu(){
int choice=0;
Scanner kb = new Scanner(System.in);
String[] args = {};
while(true){
System.out.println("Menu ");
System.out.println("1. Make Guess");
System.out.println("2. List Winner");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = kb.nextInt();
if (choice==0){
System.out.print("Do you want to play a new game? Y/N: ");
String ans = kb.next();
if (ans.equals ("Y") || ans.equals ("y")){
main(args);
}
break;
}
switch (choice){
case 1: makeGuess(); break;
case 2: listWinner(); break;
default: System.out.println("Invalid choice");
}
}
System.out.println("End of program");System.exit(0);
}
public static void makeGuess(){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int secret = rand.nextInt(10)+1;
for (int i=0; i < guessesArray.length; i++){
System.out.print("Enter your guess "+playersArray[i]+": ");
guessesArray[i]=kb.nextInt();
}
int diff = (int)(Math.abs(guess - secret));
int score=0;
if (diff == 0){
score=score+10;
}else if(diff<=1){
score=score+5;
}else if(diff<=2){
score=score+2;
}
for (int i=0; i< currscoresArray.length; i++){
currscoresArray[i]=score;
}
System.out.println();
System.out.println("Generated number is "+secret);
System.out.println("Current Score Listing");
System.out.println(" Name Guess Score Added Final Score");
System.out.println("1. "+playersArray[0]+" \t "+guessesArray[0]+" \t"+currscoresArray[0]+"");
System.out.println("1. "+playersArray[1]+" \t "+guessesArray[1]+" \t"+currscoresArray[1]+"");
}
public static void listWinner(){
}
}
just reuse a int x variable when printing from each array?
for( int x = 0; x < playersArray.length; x++ ) {
System.out.println( playersArray[ x ] + ” ” + guessArray[ x ] + " " + finalScoresArray[ x ] );
}
you already give an example in your code where you print the 3 values with a single print method. you used a for loop for indexing an element in an array. So combing the 2 techniques shouldn't be too difficult to grasp.
Instead of using an enhanced for loop (e.g. for (String player : playersArray) {}, you can use an indexed one:
for (int i = 0; i < playersArray.length; i++) {
String name = playerArray[i];
double score = scoresArray[i];
}
That being said, you should really make a Player class, that holds all information of a single player, and then have just one array, of that type. That's much nicer, not only because you can use enhanced fors, but because you don't need to make sure the arrays are always synced, and your code becomes way easier to understand.

How to compare enum value to scanner input in java for switch statement

Im' trying to get user input if he presses "a", he can do the average, calls in average method if he types in "s", he uses the sum method.
Im new to enums so im experimenting. I made an enum that stores a,b and am trying to compare it's values to user input using scanner.
I could be using if statements and forget the whole enum thing but i want to know how it works.
thanks.
public enum RecursionEnum {
s, a
}
main class:
import java.util.*;
public class Recursion {
static RecursionEnum enumtest;
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (enumtest) {
case a:
average();
case s:
sums();
}
}
public static void main(String[] args) {
yn();
}
public static int sums() {
int i = 0;
int j = 0;
int sum = i + j;
return sum;
}
public static double average() {
Scanner avgs = new Scanner(System.in);
System.out.println("Enter total number of numbers; ");
double tnum = avgs.nextDouble();
double[] nums = new double[(int) tnum];
double sum = 0;
for (int i = 0; i < tnum; i++) {
System.out.println("Enter number " + (i + 1) + " : ");
nums[i] = avgs.nextDouble();
sum += nums[i];
}
System.out.println(" ");
double avg = sum / tnum;
return avg;
}
}
This is the output:
Enter a for average or s for sum
a
Exception in thread "main" java.lang.NullPointerException
at com.towerdef.shit.Recursion.yn(Recursion.java:14)
at com.towerdef.shit.Recursion.main(Recursion.java:26)
Enumerable types have a synthetic static method, namely valueOf(String), which will return an enum instance matching the input, if it exists. Note that the input is case-sensitive in this case. Trim is used to deal with potential extraneous whitespace.
You can switch on that:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (RecursionEnum.valueOf(answer.trim())) {
case a:
average();
case s:
sums();
}
}
Of course, on Java 7 and higher, you can switching on strings. You may thus use:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (answer.trim()) {
case "a":
average();
break;
case "s":
sums();
break;
}
}

How do I show the values in both dimensional arrays?

I want to insert Coordinate x and y into both dimensional arrays and print it out. For the example given to the given code when it asks for input it doesn't do it once but twice then accepts the value. I don't if the values are actually getting stored in each array or just one. Is it possible to show output independently of the matrix? I aprecciate any help or corrections! Bless you.
Here's the code:
Code
import java.util.Scanner;
public class MummyMadness {
public static void main(String []args){
int [][] desert = new int [1][1];
int x =0;
int y =0;
int mummies[] = new int [1];
int Mlimit = 100000;
coordinates(desert,mummies,x,y);
}
public static int[] inputmummy(int mummies[], int Mlimit){
int i;
Scanner input = new Scanner(System.in);
System.out.println("How many mummies you want?");
System.out.println("Note that the limit of mummies is 100k");
i = input.nextInt();
if(mummies[i] > Mlimit)
{
System.out.println("You exceeded from the mummies!");
}
return mummies;
}
public static int[][] coordinates(int desert[][],int mummies[], int x, int y){
//Idea use length of mummies for coordinates but if you take out desert i doesnt work
System.out.println("Enter mummy coordinates");
for(int i = 0; i < desert.length; i++){
System.out.println("Enter x:");
Scanner input = new Scanner(System.in);
if(input.nextInt() > desert.length)
{
System.out.println("Error x exceeded desert length");
break;
}
desert[i][0] = input.nextInt();
System.out.println("Mummy location x: " + desert[i][0]);
for(int j = 0; j < mummies.length; j++){
System.out.println("Enter y:");
Scanner input2 = new Scanner(System.in);
if(input.nextInt() > desert[0].length)
{
System.out.println("Error y exceeded desert length");
break;
}
desert[0][j] = input2.nextInt();
System.out.println("Mummy location y: " + desert[0][j]);
System.out.println(desert[i][j])
}
}
return desert;
}
}
You are using input.nextInt twice() - once for checking and once for actually inserting into array. Everytime you call this function, it expects an input. Hence its asking for input twice.
Do this instead:
int tmp = input.nextInt();
if(tmp > desert.length)
{
System.out.println("Error x exceeded desert length");
break;
}
desert[i][0] = tmp;

Categories