comparing two arrays, increasing counter - java

I'm having problems realizing why my counter keeps printing out a different value even when I enter all the right answers. I've tried everything I could think of plus researching and still no luck. Please help, this is hour 14 of me working on this "simple" program.
import java.util.Scanner; //import scanner
public class DriverTestBlah {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
char[] correctAnswers = {'A','D','C','A','A','D','B',
'A','C','A','D','C','B','A','B'};
char singleAnswer = ' ';
int number_Correct = 0;
for(int i = 0; i < 15; i++) //print question numbers/takes user input
{
System.out.println("Question " + (i + 1) + ":");
singleAnswer = input.nextLine().charAt(0);
}//end of for loop
System.out.println("number correct: " +
total_correct_answers(correctAnswers, singleAnswer));
}//end of main
public static int total_correct_answers(char []correctAnswers,char singleAnswer){
int number_correct = 0;
for (int i = 0; i < 15; i++){
if(correctAnswers[i] == singleAnswer){
number_correct++;}
}//end of for loop
return number_correct;
}//end of correct method
}//end of class

The reason your program was showing wrong value is singleAnswer variable stores only the last value/answer given by user.
I have created an array userAnswer to store all answers given.
Try this:
public class DriverTestBlah {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
char[] correctAnswers = {'A','D','C','A','A','D','B',
'A','C','A','D','C','B','A','B'};
char[] userAnswer = new char[correctAnswers.length];
for(int i = 0; i < 15; i++) //print question numbers/takes user input
{
System.out.println("Question " + (i + 1) + ":");
userAnswer [i] = input.nextLine().charAt(0);
}//end of for loop
System.out.println("number correct: " + total_correct_answers(correctAnswers, userAnswer));
input.close();
}//end of main
public static int total_correct_answers(char []correctAnswers,char [] userAnswer) {
int number_correct = 0;
for (int i = 0; i < 15; i++){
if(correctAnswers[i] == userAnswer[i]){
number_correct++;
}
}//end of for loop
return number_correct;
}//end of correct method
}//end of class

For every question you have the correct answers in the array correctAnswers and user-answer where? In this mode in singleAnswer you save only the last answer of user and check it for every answer.
To solve this problem you can create an array of char of singleAnswer like that:
char[] singleAnswer=new char[15];
And the result add in the array:
singleAnswer[i]=input.nextLine().chatAt(0);
After you can see if the result is correct with this instruction in the for loop:
if(singleAnswer[i]==correctAnswers[i]) number_correct++;

Related

Using a for loop to call a character method multiple times. The for loop will then convert each character to a string

The output should look like the attached screenshot. I am stuck on the very last step. Using a for loop to call the getCharacter method 10 times and converting the characters to a string using the Character.toString() method.
``
public static void main(String[] args) {
int count = countNumbers();
countPlay(count);
String word = getCharacter();
stringOf10(word);
}
public static double getRealNumber(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a real number, one that has a decimal point: ");
double realNumber = sc.nextDouble();
return realNumber;
}
public static int countNumbers(){
int count = 0;
do{
if (getRealNumber() == -1.0)
break;
count++;
} while(true);
System.out.println("The count is " + count);
return count;
}
public static int countPlay(int count){
int exponent = 4;
double result = 0;
result = Math.pow(count, exponent);
System.out.println(count + "^" + exponent + " is " + result );
return count;
}
public static char getCharacter(){
Scanner input = new Scanner(System.in);
System.out.println("You will be asked to enter 10 characters.");
System.out.print("Enter a character: ");
char character = input.next().charAt(0);
return character;
}
public static char stringOf10(String word){
char i = getCharacter();
i = Character.toString(word) ;
for (i = 0; i < 10; i++){
}
return word;
}
}
``
Consider the following block of code which will run in the main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = "";
//Print the instructions before the loop
System.out.println("You will be asked to enter 10 characters.");
//request characters inside the loop
for (int i = 0; i < 10; i++){
System.out.print("Enter a character: ");
word += input.next().charAt(0);
}
//print the result (or return from a method)
System.out.println("The word is: " + word);
//return word;
}
Besides the corrections in comments, note how we create a local variable word, and simply update/append that inside the for loop word += input.next().charAt(0);.
You can easily move this code to fit your needs and return the value to be printed:
public static void main(String[] args) {
//Call the method to get our word and save the result
String result = stringOf10();
//Print the result
System.out.println("The word is: " + result);
}
public static String stringOf10(){
//Creater a scanner once before the loop
Scanner input = new Scanner(System.in);
//Create a local variable to store the word as it is updated
String word = "";
//Print the instructions once before the loop
System.out.println("You will be asked to enter 10 characters.");
//Create a loop that will run 10 times "for (int i = 0; i < 10; i++)"
//The loop starts by creating an int that is 0 "int i=0"
//Each time the loop ends it will do "i = i+1"
//The loop will run until i is no longer less than 10 "i < 10"
//Once that happens the loop will end and the code after the loop will run
for (int i = 0; i < 10; i++){
//Dach time the loop will call this method and update the word
word += getCharacter(input);
}
return word;
}
public static char getCharacter(Scanner input){
//Each time this method is called we prompt the user to enter a character
System.out.print("Enter a character: ");
//We then return the character to the previous method
return input.next().charAt(0);
}

Java: Printing trailing spaces

I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:
4
1 4 3 2
The code will need to reverse the second input to the following:
2 3 4 1
My solution is as follow:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
System.out.print(arr[reverse_i]);
if(reverse_i != 0){System.out.print(" ");}
}
}
My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.
The easy way to reverse a string is using the StringBuilder class:
One option is to remove the spaces at the end of the string eg. remove last char
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
if (arr_i != 3
sb.append(" ");
}
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
First reverse the array and then print it with a for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++)
{
arr[arr_i] = in.nextInt();
}
for(int i = 0; i < arr.length / 2; i++)
{
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
It is all about output formatting. You may use this examples and become familiar with all possible approaches.
Your code can be improved in next two ways :
1) Use \t instead of Empty Space (\t is a tabulation)
2) Create a constant with output format like this private static final String output = "%d " and use it in output line like this : String.format(output, number) where number is your number that should be printed.

program that reads integers between 1 and 100 and counts the occurrence of each

Write a program that reads integers between
1 and 100 and counts the occurrence of each (you should store the numbers in an array). Output should be in ascending order. Assume the input ends when the user enters a 0.
Hi guys, I know that this question has been posted before, perhaps a lot of times, but as I am a complete beginner at java, I don't completely understand the complexity of the codes that are posted. I just started taking Java classes, and would appreciate if you could help me figure out how to get my program to output the correct occurrences at the end. I'm so close to getting the answer but I can't figure it out for the life of me!! Thanks in advance!
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
//declarations
int [] myArray = new int [100];
int input = 5;
Scanner keyboard = new Scanner(System.in);
//input and processing
System.out.println("Please enter integers between 1 and 100 (enter 0 to stop): ");
while (input != 0)
{
input = keyboard.nextInt();
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] = input;
}
}
}
//output (This is where I need help!!!!)
for (int k = 0; k < myArray.length; k++)
{
if (myArray[k] != 0)
{
System.out.print(k + " occurs " + myArray[k] + " time");
if (myArray[k] > 1)
{
System.out.println("s");
}
else
System.out.println("");
}
}
keyboard.close();
}
}
You are storing the number entered by the user in the array. Instead, you should store a counter in each position of the array for the corresponding integer. When the user inputs a number, you should increase the corresponding counter.
The second part of your code (output results) seems ok. It is the first one that needs fixing.
I think the first for loop should be something like this:
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] += 1;
}
}
}
This should store add 1 to the array everytime the numbers occurs.
hey this my source code that worked out or me.
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// ask for user to input numbers
System.out.println("Enter some integers between 1 and 100 (and 0 when done): ");
int[] myArray = new int[1000];//create a new array for user inputs
int number;//variable for user inputs
int count = 0;
do
{
number = input.nextInt();
myArray[count] = number;
count++;
}
while (number != 0);
int[] mySort = new int [count - 1]; //create a new array with only the numbers
for(int i = 0; i< (count-1); i++) { //get the array until 0th number into new
mySort[i] = myArray[i];
}
java.util.Arrays.sort(mySort);// sort the array in ascending order
int n = 0;
for(int i = 0; i < mySort.length; i++) {//check if the number have checked before
int occurance = 0;
if(n >= mySort[i]) {
continue;
}
else {
n = mySort[i];//if a new number found do the calculation+
for (int j=0; j<mySort.length; j++)
if (n == mySort[j])
occurance++;
System.out.print(n + " occurs " + occurance );
{
if (occurance == 1) {
System.out.println(" time.");
}
else {
System.out.println(" times.");
}
}
}
}
}
}

Java program keeps exiting program prematurely

I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class
Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()

How can I print out the int values from the array?

The code below shows my progress, but I cannot print the numbers that were entered. I don't know where to put println("you entered the following numbers") in the loop so that it'll show up when the loop stops.
import java.util.Scanner;
public class aufgabe5 {
public static void main(String[] args) {
int x;
Scanner input = new Scanner(System.in);
System.out.println("How much numbers do you want to enter?");
x = input.nextInt();
int j = 1;
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[x];
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + j++ + ". number:");
numbers[i] = scanner.nextInt();
}
System.out.println("You entered following numbers");
System.out.println(x);
}
}
Change x like
System.out.println(x);
to Arrays.toString(int[]) like
System.out.println(Arrays.toString(numbers));
Edit
To print the array reversed,
String str = Arrays.toString(numbers).replace(", ", " ,");
str = str.substring(1, str.length() - 1);
System.out.println(new StringBuilder(str).reverse().insert(0, "[")
.append("]"));
Intialize the String before the loop, then keep adding the values to it.
After the loop finishes you can print the whole thing.
String someVar="You entered following numbers: ";
for(int 1=0;i<array.length;i++)
{
someVar=someVar+numbers[i]+",";
}
System.out.println(someVar);

Categories

Resources