PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label java.util.scanner. Show all posts
Showing posts with label java.util.scanner. Show all posts

Monday, November 14, 2022

[FIXED] How to check if each element in a string array is an integer?

 November 14, 2022     arrays, error-handling, integer, java, java.util.scanner     No comments   

Issue

I'm attempting an error check that determines whether all the the elements of an array are integers, i've been stuck for a long time though. any ideas on how to get started would be helpful.

Scanner scan = new Scanner(System.in);

System.out.print("Please list at least one and up to 10 integers: ");
String integers = scan.nextLine();

String[] newArray = integers.split("");

Solution

Using the String you made with the scanner, loop over a space-delimited list and check that each element is an integer. If they all pass, return true; otherwise return false.

Credit for the isInteger check goes to Determine if a String is an Integer in Java

public static boolean containsAllIntegers(String integers){
   String[] newArray = integers.split(" ");
   //loop over the array; if any value isnt an integer return false.
   for (String integer : newArray){
      if (!isInteger(integer)){
         return false;
      }   
   }   
   return true;
}

public static boolean isInteger(String s) {
  try { 
      Integer.parseInt(s); 
   } catch(NumberFormatException e) { 
      return false; 
   }
   // only got here if we didn't return false
   return true;
}


Answered By - astennent
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, October 30, 2022

[FIXED] How to save stdin data into class/object [JAVA]

 October 30, 2022     class, eof, java, java.util.scanner, object     No comments   

Issue

I want to use a Class to hold user inputs. For example "example_name";"example_value";"example_city" is the form of the input and I want to make objects from an input stream of theese three inputs line by line from a file. So whenever I enter Adam;27; London it should be saved into an Object(Adam,27,London) and ask for the next input. Thank you for your help, I know this might be a stupid question but I'm new to OO programming and I have a C background and don't want to use two dimensional arrays.


Solution

Let's break this problem into 3 section. First, we will have to design the class. Second, we will take the user input and create an object of that class until the user press n(no). Third, we will display the user information. Here I have used a LinkedList data structure for storing the inputs.

Section 1:

class example{

   String example_name; 
    int example_value;
    String example_city;
    example(String name,int value,String city)
    {
        this.example_name = name;
        this.example_value = value;
        this.example_city = city;
    }
}

section 2:

 LinkedList<example> ob = new LinkedList<>();
        Scanner input = new Scanner(System.in);

        System.out.println("Press y to Continue n to Exit");
        char i = input.next().charAt(0);
        while(i!='n')
        {
            input.nextLine();
            System.out.println("Enter name");
            String name = input.nextLine();
            System.out.println("Enter value");
            int value = input.nextInt();
            input.nextLine();
             System.out.println("Enter city");
            String city = input.nextLine();
            ob.addLast(new example(name,value,city));
            System.out.println("Press y to Continue n to Exit");
             i = input.next().charAt(0);
        }

Section 3:

 for(example x:ob)
             System.out.println(x.example_name + " " + x.example_value + " "+x.example_city);


Answered By - suvojit_007
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 29, 2022

[FIXED] How to use hasNext() from the Scanner class?

 October 29, 2022     eof, java, java.util.scanner     No comments   

Issue

Input Format

Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.

Output Format

For each line, print the line number, followed by a single space, and then the line content received as input:

Sample Output

Hello world
I am a file
Read me until end-of-file.  

Here is my solution. The problem being I am not able to proceed till EOF. But the output is just:

Hello world

Here is my code:

public class Solution {

    public static void main(String[] args) {
        check(1);  // call check method
    }

    static void check(int count) {          
        Scanner s = new Scanner(System.in);
        if(s.hasNext() == true) {
            String ns = s.nextLine();
            System.out.println(count + " " + ns);
            count++;
            check(count);
        }
    } 
}

Solution

Your code does not work because you create a new Scanner object in every recursive call. You should not use recursion for this anyways, do it iteratively instead.

Iterative version

public class Solution {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        int count = 1;

        while(s.hasNext()) {
            String ns = s.nextLine();
            System.out.println(count + " " + ns);
            count++;
        }
    }
}

Recursive version

public class Solution {

    private Scanner s;

    public static void main(String[] args) {

        s = new Scanner(System.in); // initialize only once
        check(1);
    }

    public static void check(int count) {
        if(s.hasNext()) {
            String ns = s.nextLine();
            System.out.println(count + " " + ns);
            check(count + 1);
        }
    }   
}


Answered By - Willi Mentzel
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 4, 2022

[FIXED] How to make a library of string arrays and access them like a login system. (Java 17)

 September 04, 2022     authentication, eclipse, java, java-17, java.util.scanner     No comments   

Issue

I am trying to make a login prompt with usernames and passwords, but I cannot figure out how to make the string array library. My current code can take in 1 username and password by using functions with variables, (like public myFunction(String myVariable);) and login with just that, and change the pass and username. currently, my code is

package main;

import java.util.Scanner;
import logins.Logins;

public class Main {
    public static void main(String[] args) {
        String choice = null;
        Scanner scanner = null;
        start(choice, scanner, "Password", "Username");
    }
    
    public static void command(String choice, Scanner scanner, String pass, String user) {
        if(choice.equals("login")) { 
            login(pass, scanner, choice, user);
        }else if(choice.equals("change password")) {
            passChange(pass, choice, scanner, user);
        }else if(choice.equals("change username")) {
            userChange(pass, choice, scanner, user);
        }else {
            System.err.println("Invalid choice");
            start(choice, scanner, pass, user);
        }
    }
    
    public static void password(String pass, String choice, Scanner scanner, String user) {
        System.out.println("Enter password");
        choice = scanner.nextLine();
        if(choice.equals(pass)) {
            System.out.println("Password Correct. You are logged in");
            start(choice, scanner, pass, user);
        }else {
            System.err.println("Incorrect Password");
            start(choice, scanner, pass, user);
        }
    }
    
    public static void passChange(String pass, String choice, Scanner scanner, String user) {
        System.out.println("Username:");
        choice = scanner.nextLine();
        if (choice.equals(user)) {
            System.out.println("Old Password:");
            choice = scanner.nextLine();
            if (choice.equals(pass)) {
                System.out.println("New Password");
                choice = scanner.nextLine();
                pass = choice;
                start(choice, scanner, pass, user);
            }else {
                System.err.println("Incorrect password");
                start(choice, scanner, pass, user);
            }
        }else {
            System.err.println("No user found named " + choice);
            start(choice, scanner, pass, user);
        }
    }
    
    public static void userChange(String pass, String choice, Scanner scanner, String user) {
        System.out.println("Username:");
        choice = scanner.nextLine();
        if (choice.equals(user)) {
            System.out.println("Password:");
            choice = scanner.nextLine();
            if (choice.equals(pass)) {
                System.out.println("Logged in. New username:");
                choice = scanner.nextLine();
                user = choice;
                start(choice, scanner, pass, user);
            }else {
                System.err.println("Incorrect password");
                start(choice, scanner, pass, user);
            }
        }else {
            System.err.println("Incorrect password");
            start(choice, scanner, pass, user);
        }
    }
    
    public static void start(String choice, Scanner scanner, String pass, String user) {
        scanner = new Scanner(System.in);
        System.out.println("What would you like to do? ");
        choice = scanner.nextLine();
        command(choice, scanner, pass, user);
    }
    public static void login(String pass, Scanner scanner, String choice, String user) {
        System.out.println("Enter username");
        choice = scanner.nextLine();
        if(choice.equals(user)) {
            System.out.println("Valid Username.");
            password(pass, choice, scanner, user);
        }else {
            System.err.println("No user named " + choice);
            start(choice, scanner, pass, user);
        }
    }
}

I have started making an array library, but I don't know how to access any of the usernames or passwords in general,(like once you put in a username, it gets the matching password)

package logins;

public class Logins {
    public static void main(String[] args) {
        String[] User = new String[] {"Username", "Password"};
        String[] User1 = new String[] {"Username1", "Password1"};
    }
}


Solution

Are you trying to link Usernames and Passwords together? If so, try using a HashMap. You could try doing something like:

HashMap<String, String> logins= new HashMap<String, String>();

This way a username can retrieve the corresponding password

String password = logins.get("Mario");

Though getting passwords from usernames would not be recommended. You could add to it by:

logins.put("Mario", "password1234");

Not sure if this is what you were asking but hope this helps



Answered By - Loïc Rutabana
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make a library of string arrays and access them like a login system. (Java 17)

 September 04, 2022     authentication, eclipse, java, java-17, java.util.scanner     No comments   

Issue

I am trying to make a login prompt with usernames and passwords, but I cannot figure out how to make the string array library. My current code can take in 1 username and password by using functions with variables, (like public myFunction(String myVariable);) and login with just that, and change the pass and username. currently, my code is

package main;

import java.util.Scanner;
import logins.Logins;

public class Main {
    public static void main(String[] args) {
        String choice = null;
        Scanner scanner = null;
        start(choice, scanner, "Password", "Username");
    }
    
    public static void command(String choice, Scanner scanner, String pass, String user) {
        if(choice.equals("login")) { 
            login(pass, scanner, choice, user);
        }else if(choice.equals("change password")) {
            passChange(pass, choice, scanner, user);
        }else if(choice.equals("change username")) {
            userChange(pass, choice, scanner, user);
        }else {
            System.err.println("Invalid choice");
            start(choice, scanner, pass, user);
        }
    }
    
    public static void password(String pass, String choice, Scanner scanner, String user) {
        System.out.println("Enter password");
        choice = scanner.nextLine();
        if(choice.equals(pass)) {
            System.out.println("Password Correct. You are logged in");
            start(choice, scanner, pass, user);
        }else {
            System.err.println("Incorrect Password");
            start(choice, scanner, pass, user);
        }
    }
    
    public static void passChange(String pass, String choice, Scanner scanner, String user) {
        System.out.println("Username:");
        choice = scanner.nextLine();
        if (choice.equals(user)) {
            System.out.println("Old Password:");
            choice = scanner.nextLine();
            if (choice.equals(pass)) {
                System.out.println("New Password");
                choice = scanner.nextLine();
                pass = choice;
                start(choice, scanner, pass, user);
            }else {
                System.err.println("Incorrect password");
                start(choice, scanner, pass, user);
            }
        }else {
            System.err.println("No user found named " + choice);
            start(choice, scanner, pass, user);
        }
    }
    
    public static void userChange(String pass, String choice, Scanner scanner, String user) {
        System.out.println("Username:");
        choice = scanner.nextLine();
        if (choice.equals(user)) {
            System.out.println("Password:");
            choice = scanner.nextLine();
            if (choice.equals(pass)) {
                System.out.println("Logged in. New username:");
                choice = scanner.nextLine();
                user = choice;
                start(choice, scanner, pass, user);
            }else {
                System.err.println("Incorrect password");
                start(choice, scanner, pass, user);
            }
        }else {
            System.err.println("Incorrect password");
            start(choice, scanner, pass, user);
        }
    }
    
    public static void start(String choice, Scanner scanner, String pass, String user) {
        scanner = new Scanner(System.in);
        System.out.println("What would you like to do? ");
        choice = scanner.nextLine();
        command(choice, scanner, pass, user);
    }
    public static void login(String pass, Scanner scanner, String choice, String user) {
        System.out.println("Enter username");
        choice = scanner.nextLine();
        if(choice.equals(user)) {
            System.out.println("Valid Username.");
            password(pass, choice, scanner, user);
        }else {
            System.err.println("No user named " + choice);
            start(choice, scanner, pass, user);
        }
    }
}

I have started making an array library, but I don't know how to access any of the usernames or passwords in general,(like once you put in a username, it gets the matching password)

package logins;

public class Logins {
    public static void main(String[] args) {
        String[] User = new String[] {"Username", "Password"};
        String[] User1 = new String[] {"Username1", "Password1"};
    }
}


Solution

Are you trying to link Usernames and Passwords together? If so, try using a HashMap. You could try doing something like:

HashMap<String, String> logins= new HashMap<String, String>();

This way a username can retrieve the corresponding password

String password = logins.get("Mario");

Though getting passwords from usernames would not be recommended. You could add to it by:

logins.put("Mario", "password1234");

Not sure if this is what you were asking but hope this helps



Answered By - Loïc Rutabana
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 5, 2022

[FIXED] how to solve NoSuchElementException Error in Scanner of Java?

 August 05, 2022     exception, java, java.util.scanner, nosuchelementexception     No comments   

Issue

I am making a simple console game where player is allowed to move in x ,-x, y,-y directions according to String input collected from keyboard as a, d, w and s respectively , but scanner is throwing NoSuchElementException, I tried collecting data with nextInt() too ,but I was getting similar exception. Note: But scanner works for one time i.e. first time.

My Code

   private static void gamePlay(boolean isPlaying) {

    while (isPlaying) {

        System.out.println("Choose a, d , s or w for movement:");
        Scanner sc = new Scanner(System.in);
        String choice = sc.next();
        sc.close();
        // code for movement of player according to a or s or d or w
        switch (choice) {
            case "a":
                // Some code here
                // move -x
                break;

            case "d":
                // Some code here
                // move +x

                break;

            case "w":
                // Some code here
                // move +y

                break;

            case "s":
                // Some code here
                // move -y

                break;
            case "q":
                //quit 
                isPlaying = false;
                break;

            default:
                break;

        }

    }

}

** Output**

    Choose a, d , s or w for movement:
    a
    Choose a, d , s or w for movement:
    Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at App.gamePlay(App.java:37)
    at App.main(App.java:17)

Solution

private static void gamePlay(boolean isPlaying) {

    while (isPlaying) {

        System.out.println("Choose a, d , s or w for movement:");
        Scanner sc = new Scanner(System.in);
        String choice = sc.next();
        // code for movement of player according to a or s or d or w
        switch (choice) {
            case "a":
                // Some code here
                // move -x
                break;

            case "d":
                // Some code here
                // move +x

                break;

            case "w":
                // Some code here
                // move +y

                break;

            case "s":
                // Some code here
                // move -y

                break;
            case "q":
                //quit
                sc.close();
                isPlaying = false;
                break;

            default:
                break;
        }

    }
}


Answered By - rlowell
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 21, 2022

[FIXED] How to find max number and occurrences

 July 21, 2022     integer, java, java.util.scanner, loops, while-loop     No comments   

Issue

So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .

my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.

But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .

 package myjavaprojects2;
import java.util.*;
public class Max_number_count {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        int count = 0;
        int max = 1;
        System.out.print("Enter a Integer:");
        int userInput = input.nextInt();    

        while ( userInput != 0) {
           
                        
        if (userInput > max) {
            int temp = userInput;
            userInput = max;
            max = temp;
         } else if (userInput == max) {
             count++ ;
             
             
         }
             
    
        System.out.println("The max number is " + max );
        System.out.println("The count is " + count );
        }
      }
    }

Solution

So how do you take multiple inputs from the user on the same line .

You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.

 int userInput = input.nextInt();    

    while ( userInput != 0) {
      //all above logic
      userInput = input.nextInt();        
    }


Answered By - Manh Nguyen
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing